我有一个复选框的活动:如果chekbox的勾选,那么停止该服务。这是我的活动code的一个片段:
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);
当我停止服务,我传递一个参数user_stop在那一直是用户停止它,而不是系统(低内存)的服务的话。
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).
现在我要读我的服务空白的onDestroy变量user_stop:
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 ****
,但它不工作!在我的onDestroy不能使用getIntent()!
but it doesn't work! I can't use getIntent() in onDestroy!
任何建议?
感谢
西蒙尼
我认为这样做的两种方式:
I see two ways of doing this:
在使用共享preferences。 在利用当地的广播。第一种方法是一种简单而直接的方式。但它不是很灵活。基本上,你做的:
The first approach is an easy and straightforward way. But it is not very flexible. Basically you do:
一个。设置用户停止共享preference为true。 乙。停止服务 ℃。在你的onDestroy服务检查什么是用户停止preference值。另一种方法是一个更好的办法,但需要更多的code。
The other approach is a better way but requires more code.
一个。定义一个字符串常量在您的服务类:final public static string USER_STOP_SERVICE_REQUEST = "USER_STOP_SERVICE".
乙。创建一个内部类BroadcastReceiver的类:
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
}
}
℃。注册该接收机的onCreate或OnStart方法:
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.