如何将参数从活动传递到服务...当用户停止服务时

Sim*_*one 3 parameters service android ondestroy android-activity

我有一个带有复选框的活动:如果取消选中chekbox,则停止服务.这是我的活动代码的片段:

    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.android.savebattery.SaveBatteryService");

    if (*unchecked*){
        serviceIntent.putExtra("user_stop", true);
        stopService(serviceIntent);
Run Code Online (Sandbox Code Playgroud)

当我停止服务时,我传递一个参数"user_stop"来说明已经是用户停止它的服务,而不是系统(用于低内存).

现在我必须在我的服务的void onDestroy中读取变量"user_stop":

public void onDestroy() {
super.onDestroy();

Intent recievedIntent = getIntent(); 
boolean userStop= recievedIntent.getBooleanExtra("user_stop");

    if (userStop) {
       *** notification code ****
Run Code Online (Sandbox Code Playgroud)

但它不起作用!我不能在onDestroy中使用getIntent()!

有什么建议吗?

谢谢

西蒙娜

ina*_*ruk 6

我看到两种方法:

  1. 使用共享首选项.
  2. 使用本地广播.

第一种方法是简单直接的方法.但它不是很灵活.基本上你做:

  • 一个.将"user stop"共享首选项设置为true.
  • 湾 停止服务
  • C.在onDestroy服务中检查"用户停止"首选项的值是什么.

另一种方法是更好的方法,但需要更多的代码.

  • 一个.在服务类中定义字符串常量:
final public static string USER_STOP_SERVICE_REQUEST = "USER_STOP_SERVICE".
Run Code Online (Sandbox Code Playgroud)
  • 湾 创建一个内部类BroadcastReceiver类:

    public class UserStopServiceReceiver extends BroadcastReceiver  
    {  
        @Override  
        public void onReceive(Context context, Intent intent)  
        {  
            //code that handles user specific way of stopping service   
        }  
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • C.在onCreate或onStart方法中注册此接收器:

    registerReceiver(new UserStopServiceReceiver(),  newIntentFilter(USER_STOP_SERVICE_REQUEST));
    Run Code Online (Sandbox Code Playgroud)
  • d.从您想要停止服务的任何地方:

    context.sendBroadcast(new Intent(USER_STOP_SERVICE_REQUEST));
    Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用此方法通过Intent传递任何自定义参数.