android - 无法销毁android中的服务

标签 android service destroy

在我的应用程序中,我根据服务器响应给出了大雨通知。但我无法破坏服务并停止通知。我已停止取消选中复选框的通知。在我的代码中调用 onDestroy 方法并显示 toast 消息但服务没有停止。我怎样才能做到这一点。提前致谢

Alert_notifications.java

public class Alert_notifications extends Activity {
     CheckBox enablecheck;
    /** Called when the activity is first created. */
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_notifications);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        enablecheck = (CheckBox)findViewById(R.id.checkBox1);            

        enablecheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {


            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                // TODO Auto-generated method stub
                if(enablecheck.isChecked()){    
                // TODO Auto-generated method stub
                Intent intent = new Intent(Alert_notifications.this, com.example.gpstracking.NotifyService.class);
                Alert_notifications.this.startService(intent);
                }
                else
                {
                    stopService(new Intent(Alert_notifications.this, NotifyService.class));

                }                       
            }

        });
    }



NotifyService.java (service)

    public class NotifyService extends Service {

        NotifyServiceReceiver notifyServiceReceiver;
        final static String ACTION = "NotifyServiceAction";
        final static String STOP_SERVICE = "";
        final static int RQS_STOP_SERVICE = 1;
        private static final String url_Weather_details1="http://128.251.238.238/Weatherforecast1/";
        private static final String TAG_SUCCESS = "success";
        private static Timer timer = new Timer(); 
        private Context ctx;
        private static final int MY_NOTIFICATION_ID = 1;
        private NotificationManager notificationManager;
        private Notification myNotification;

        // constant
        public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds

        // run on another Thread to avoid crash
        private Handler mHandler = new Handler();
        // timer handling
        private Timer mTimer = null;

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            // cancel if already existed
            if(mTimer != null) {
                mTimer.cancel();
            } else {
                // recreate new
                mTimer = new Timer();
            }
            // schedule task
            mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
        }

        class TimeDisplayTimerTask extends TimerTask {

            @Override
            public void run() {
                // run on another thread
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        if(isNetworkAvailable())
                        {
                        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                        JSONParser jsonParser = new JSONParser();
                        params.add(new BasicNameValuePair("LAT", "LAT"));
                        params.add(new BasicNameValuePair("LONGITUDE", "LONG"));
                        Log.d("params", params.toString());
                        // getting weather details by making HTTP request
                        // Note that weather details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(url_Weather_details1,
                                "GET", params);
                        // check your log for json response
                        Log.d("Weather Details", json.toString());

                        // json success tag
                        int success = 0;
                        try {
                            success = json.getInt(TAG_SUCCESS);
                            System.out.println("success"+success);
                        } 
                        catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if (success == 2) {
                            // successfully received weather details

                        // TODO Auto-generated method stub

                        IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(ACTION);
                        registerReceiver(notifyServiceReceiver, intentFilter);

                        // Send Notification
                        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        myNotification = new Notification(R.drawable.heavy_rain,"Heavy rain", System.currentTimeMillis());

                        Context context = getApplicationContext();
                        String notificationTitle = "Heavy Rain!";
                        String notificationText = "";
                        Intent myIntent=new Intent(context, Alert_activity.class);
                        //Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
                        PendingIntent pendingIntent = PendingIntent.getActivity(
                                getBaseContext(), 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
                        myNotification.defaults |= Notification.DEFAULT_SOUND;
                        myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
                        myNotification.setLatestEventInfo(context, notificationTitle,
                                notificationText, pendingIntent);
                        notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

                        }

                        }

                    }

                });
            }
        }

    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    public void onDestroy(){
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
        notificationManager.cancel(MY_NOTIFICATION_ID);
        super.onDestroy();
    }

    }

最佳答案

In my code onDestroy method is called and toast message is displayed but service is not stopped

是的,是的。 没有停止的是您的TimerTimerTask 开始了 -- 需要在 onDestroy() 中停止它,可能通过调用 cancel() 计时器

关于android - 无法销毁android中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28455980/

相关文章:

java - 在拨号器应用程序顶部检测来电并在后台打开服务

python - 导入Gtk并关闭窗口后访问Gdk区域

c# - 如何销毁实例化的游戏对象克隆?

python - Tkinter 无法正确关闭并启动新文件

android - 当 RecyclerView 元素为其高度设置动画时,如何正确绘制 ItemDecoration?

service - 无法启动Docker守护程序

java - 缺少文件路径

android - 如何从 AlarmManager 启动服务

android - 获取Android App的Linux UID

c# - Android 的 Mono 无法构建 - 找不到 Novell.MonoDroid.CSharp.targets