2015-02-11 42 views
1

在我的應用程序中,我根據服務器響應給出了有關暴雨的通知。但我無法銷燬服務並停止通知。我已經停止通知,取消選中複選框。在我的代碼中調用onDestroy方法並顯示Toast消息,但服務未停止。我怎樣才能做到這一點。提前無法銷燬android中的服務

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

    } 
+0

也許乾淨你的髒計時器? =),並請清理並縮進你的代碼,它只能幫助你 – 2015-02-11 13:54:12

回答

4

在我的代碼的onDestroy方法由於被調用,顯示敬酒消息,但服務沒有停止

是的,它是。什麼是不是已停止是您的TimerTimerTask開始 - 需要在onDestroy()停止,可能通過撥打Timercancel()

+0

它的工作原理...非常感謝你... – 2015-02-11 14:17:38