【问题标题】:How to pass a parameter from an activity to a service...when the user stop the service如何将参数从活动传递给服务......当用户停止服务时
【发布时间】:2011-01-10 22:01:30
【问题描述】:

我有一个带有复选框的活动:如果未选中复选框,则停止服务。这是我的活动代码的 sn-p:

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

    if (*unchecked*){
        serviceIntent.putExtra("user_stop", true);
        stopService(serviceIntent);

当我停止服务时,我传递了一个参数“user_stop”来表示服务是用户停止它而不是系统(内存不足)。

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

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

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

    if (userStop) {
       *** notification code ****

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

有什么建议吗?

谢谢

西蒙娜

【问题讨论】:

    标签: android parameters service android-activity ondestroy


    【解决方案1】:

    我看到了两种方法:

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

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

    • 一个。将“用户停止”共享偏好设置为 true。
    • 乙。停止服务
    • c。在您的 onDestroy 服务中检查“用户停止”首选项的值。

    另一种方法更好,但需要更多代码。

    • 一个。在你的服务类中定义一个字符串常量:
    final public static string USER_STOP_SERVICE_REQUEST = "USER_STOP_SERVICE".
    • b.创建一个内部类BroadcastReceiver类:

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

      registerReceiver(new UserStopServiceReceiver(),  newIntentFilter(USER_STOP_SERVICE_REQUEST));
    • d。从您想停止服务的任何地方:

      context.sendBroadcast(new Intent(USER_STOP_SERVICE_REQUEST));

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

    【讨论】:

    • 本地广播的绝妙方法,您知道我们是否可以绑定到正在运行的服务? (用于 2way 通信)
    【解决方案2】:

    我不认为依赖 onDestroy() 是一件好事。您可以采取几种方法。

    1. 建议绑定服务,这样您就可以在 onUnbind http://developer.android.com/guide/topics/fundamentals.html#servlife

    2. 中写入用户停止通知
    3. 其他选项(不确定这是否有效)是将变量发布到 SharedPreferences 并从 onDestroy() 获取它。 [您需要检查这是否适用于调试模式或 LogCat 消息。

    【讨论】:

      【解决方案3】:

      我在我的应用程序中使用我的活动中的 CheckBoxPreference 和服务类的 onCreate 中的 getSharedPreference 进行了相同的设置。选中复选框将启动服务。取消选中会停止服务。

      在我的 Activity 中收听并处理偏好点击:

          getPreferenceManager().findPreference("prefEnable").setOnPreferenceClickListener(new OnPreferenceClickListener()
          {
              // not used: Intent intent = new Intent(this, MyService.class);
              @Override
              public boolean onPreferenceClick(Preference preference) {
                  CheckBoxPreference cb = (CheckBoxPreference) preference;
                  if (cb.isChecked()) {
                      Log.d(TAG, "User enabled service");
                      // code to start service
                  } else {
                      Log.d(TAG, "User disabled service");
                      // code to stop service
                  }
                  return true;
              }
          });
      

      在我的服务 onCreate 中获取我的“prefEnable”首选项:

          SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
          Boolean isEnabled = preferences.getBoolean("prefEnable", false);
      

      也许在你的 onDestroy 中,你可以重新调整它的用途并说:

      if (isEnabled==false) {
         *** notification code ***
      

      【讨论】:

      • 这个工作示例在我发布 3 年后被否决,为什么?
      【解决方案4】:

      // 可以这样简单的传递参数:-

      Intent serviceIntent = new Intent(this,ListenLocationService.class); 
         serviceIntent.putExtra("From", "Main");
         startService(serviceIntent);
      //and get the parameter in onStart method of your service class
      
          @Override
      public void onStart(Intent intent, int startId) {
          super.onStart(intent, startId);
           Bundle extras = intent.getExtras(); 
      if(extras == null)
          Log.d("Service","null");
      else
      {
          Log.d("Service","not null");
          String from = (String) extras.get("From");
          if(from.equalsIgnoreCase("Main"))
              StartListenLocation();
      }
      
      }
      Enjoy :)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-10
        • 1970-01-01
        相关资源
        最近更新 更多