2016-12-29 63 views
0

我從通過套接字發送數據到服務器的活動開始服務。在onCreate()方法開始服務的時候,也用setExact()方法設定報警。我的問題是當中的onReceive()被調用時,我想停止服務,它正在正常工作,但它也被重新啓動。使用下一個代碼停止服務:無法從BroadcastReceiver中終止服務

Intent i = new Intent(context, SocketService.class); 
context.stopService(i); 

如果從Activity中調用它,它將正常工作。當BroadcastReceiver被執行時,沒有任何活動綁定到該服務,所以它應該停止,而不會立即重新創建。

回答

1

您的服務。

private Intent myservice; 

啓動的方法,服務的onCreate()

myservice = new Intent(this, myservice.class); 
    startService(myservice); 

,你也可以與處理器開始爲您服務。

並停止使用處理程序。

private Handler handler = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
     switch (msg.what) { 
      case 1: 
        stopService(myservice); 
       break; 
      default: 
       Log.d("STOP", msg.what + " ? "); 
       break; 
     } 
    } 
}; 

對廣播接收器使用的處理器使這個

handler.sendEmptyMessage(1);