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

发布于 2024-10-11 15:19:35 字数 727 浏览 3 评论 0原文

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

    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() !

有什么建议吗?

谢谢西蒙娜

I have an activity with a checkbox: if the chekbox is unchecked then stop the service. this is a snippet of my activity code:

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

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

when I stop the service I pass a parameter "user_stop" to say at the service that has been a user to stop it and not the system (for low memory).

now I have to read the variable "user_stop" in void onDestroy of my service:

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

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

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

but it doesn't work! I can't use getIntent() in onDestroy!

any suggestion?

thanks

Simone

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

帅哥哥的热头脑 2024-10-18 15:19:35

我看到有两种方法可以做到这一点:

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

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

  • :将“用户停止”共享首选项设置为 true。
  • b.停止服务
  • C.在 onDestroy 的服务中检查“用户停止”首选项的值是什么。

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

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

    公共类 UserStopServiceReceiver 扩展了 BroadcastReceiver  
    {  
        @覆盖  
        公共无效onReceive(上下文上下文,意图意图)  
        {  
            //处理用户特定停止服务方式的代码   
        }  
    }
    
  • c.在 onCreate 或 onStart 方法中注册此接收器:

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

    context.sendBroadcast(new Intent(USER_STOP_SERVICE_REQUEST));

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

I see two ways of doing this:

  1. Using Shared Preferences.
  2. Using local broadcasts.

The first approach is an easy and straightforward way. But it is not very flexible. Basically you do:

  • a. Set "user stop" shared preference to true.
  • b. Stop service
  • c. In you service in onDestroy check what is the value of "user stop" preference.

The other approach is a better way but requires more code.

  • a. Define a string constant in you service class:
final public static string USER_STOP_SERVICE_REQUEST = "USER_STOP_SERVICE".
  • b. Create an inner class BroadcastReceiver class:

    public class UserStopServiceReceiver extends BroadcastReceiver  
    {  
        @Override  
        public void onReceive(Context context, Intent intent)  
        {  
            //code that handles user specific way of stopping service   
        }  
    }
    
  • c. Register this receiver in onCreate or onStart method:

    registerReceiver(new UserStopServiceReceiver(),  newIntentFilter(USER_STOP_SERVICE_REQUEST));
  • d. From any place you want to stop your service:

    context.sendBroadcast(new Intent(USER_STOP_SERVICE_REQUEST));

Note that you can pass any custom arguments through Intent using this approach.

人疚 2024-10-18 15:19:35

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

  1. 建议绑定服务,以便您可以在 onUnbind 中编写用户停止通知 http ://developer.android.com/guide/topics/fundamentals.html#servlife

  2. 其他选项(不确定这是否有效)是将变量发布到 SharedPreferences 并从 onDestroy() 获取它。 [您需要检查这在调试模式或 LogCat 消息中是否有效。

I don't think relying on onDestroy() is a good thing. There are couple of approaches you can take.

  1. suggest to bind the service so that you could write your userstop notification in onUnbind http://developer.android.com/guide/topics/fundamentals.html#servlife

  2. Other option (not sure if this works) is to post your variable to SharedPreferences and obtain it from onDestroy(). [You need to check if this works in debug mode or LogCat messages.

爱的故事 2024-10-18 15:19:35

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

监听并处理我的活动中的首选项单击:

    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 ***

I have the same setup in my app using CheckBoxPreference in my activity and getSharedPreference in service class's onCreate. Checking the checkbox starts the service. Unchecking stops the service.

Listen and handle preference click in my 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;
        }
    });

Get my "prefEnable" preference within my service onCreate:

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

Perhaps in your onDestroy, you can re-purpose this and say:

if (isEnabled==false) {
   *** notification code ***
此生挚爱伱 2024-10-18 15:19:35

// 您可以通过这种简单的方式传递参数:-

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 :)

// You can pass the parameter in this simple way:-

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 :)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文