2016-02-27 179 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 { ........' –