2016-02-27 210 views
0

有人可以請解釋我爲什麼我的服務不停止?如何在設備被鎖定時立即停止服務並永久停止。 我的活動:如何立即停止服務立即

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     startService(new Intent(this, MyService.class)); 
     IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); 
     filter.addAction(Intent.ACTION_SCREEN_ON); 
     BroadcastReceiver mReceiver = new MyReceiver(); 
     registerReceiver(mReceiver, filter); 
    } 
} 

我的收款人:

public class MyReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if(Intent.ACTION_SCREEN_ON.equals(action)) { 
      Log.i("isScreen ","on"); 
     } else 
     if(Intent.ACTION_SCREEN_OFF.equals(action)) { 
      Log.i("isScreen ","off"); 
      context.stopService(new Intent(context, MyService.class)); 
     } 
    } 
} 

我的服務:

public class MyService extends Service { 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.i("Service ","starts"); 
    } 
} 
+0

當您解鎖設備時,檢查接收器中的條件 –

+0

除非您管理該服務,否則該服務將繼續在後臺運行。 http://stackoverflow.com/a/34530513/3956566 –

+0

@ ajay-pandya你的意思是像「如果設備被解鎖,然後開始/停止服務」? –

回答

0

你已經嘗試這一個?

boolean isBound = false; 
... 
isBound = getApplicationContext().bindService(new Intent(getApplicationContext(), ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE); 
... 
if (isBound) 
    getApplicationContext().unbindService(serviceConnection); 
+0

我的服務沒有綁定。所以,感謝您的解決方案,但它不會工作。 –

+0

怎麼樣: '公共無效的onDestroy(){ Toast.makeText(這一點, 「服務被摧毀」,Toast.LENGTH_SHORT).show(); super.onDestroy(); }' in 'public class MyService extends Service { ........' –