Search code examples
androidservicedestroy

Unable to destroy service in android


In my application I have given the notifications for heavy rain based on server response. But I m unable to destroy the service and stop notifications.I have stop the notifications on the unchecking the checkbox. In my code onDestroy method is called and toast message is displayed but service is not stopped. How can I do this. Thanks in advance

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();
    }

    }

Solution

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

    Yes, it is. What is not stopped is your Timer and TimerTask. You started that -- you need to stop that in onDestroy(), probably by calling cancel() on the Timer.