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()!
有什么建议吗?
谢谢
西蒙娜
我看到两种方法:
第一种方法是简单直接的方法.但它不是很灵活.基本上你做:
另一种方法是更好的方法,但需要更多的代码.
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传递任何自定义参数.
归档时间: |
|
查看次数: |
11082 次 |
最近记录: |