我有一个小问题。
在我的应用程序中,用户成功登录后会启动一个服务。以前,如果应用程序被杀死,也就是说,通过滑动从最近的应用程序列表中删除,服务需要停止。因此,我们使用了 android:stopWithTask =“true”
。现在我们需要该服务照常运行,即使启动它的任务已从最近的应用程序列表中删除。因此,我将 Service 更改为包括 android:stopWithTask =“false”
。但这似乎不起作用。
相关代码:
下面是与服务相关的清单部分:
<service
android:enabled="true"
android:name=".MyService"
android:exported="false"
android:stopWithTask="false" />
在MyService.java文件中:
public class MyService extends AbstractService {
@Override
public void onStartService() {
Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new Notification(R.drawable.ic_launcher, "My network services", System.currentTimeMillis());
notification.setLatestEventInfo(this, "AppName", "Message", pendingIntent);
startForeground(MY_NOTIFICATION_ID, notification);
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Toast.makeText(getApplicationContext(), "onTaskRemoved called", Toast.LENGTH_LONG).show();
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
}
}
AbstractService.java 是一个扩展了 Service
的自定义类:
public abstract class AbstractService extends Service {
protected final String TAG = this.getClass().getName();
@Override
public void onCreate() {
super.onCreate();
onStartService();
Log.i(TAG, "onCreate(): Service Started.");
}
@Override
public final int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStarCommand(): Received id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
@Override
public final IBinder onBind(Intent intent) {
return m_messenger.getBinder();
}
@Override
public void onDestroy() {
super.onDestroy();
onStopService();
Log.i(TAG, "Service Stopped.");
}
public abstract void onStartService();
public abstract void onStopService();
public abstract void onReceiveMessage(Message msg);
@Override
public void onTaskRemoved(Intent rootIntent) {
Toast.makeText(getApplicationContext(), "AS onTaskRemoved called", Toast.LENGTH_LONG).show();
super.onTaskRemoved(rootIntent);
}
}
如果我登录应用程序,MyService将启动。之后我按Home按钮,应用程序就会移动到后台。现在我从“最近使用的应用程序”列表中删除应用程序。此时,根据此方法的描述,我应该看到Toast和控制台消息:public void onTaskRemoved (Intent rootIntent)
API级别14中添加
如果服务当前正在运行并且用户已删除来自服务应用程序的任务,则会调用此操作。如果您设置了ServiceInfo.FLAG_STOP_WITH_TASK,则不会收到此回调;相反,服务将被简单地停止。
参数rootIntent:启动要删除的任务的原始根Intent。
但我没有看到任何东西。 Service在onStartCommand
中返回START_STICKY,因此我认为onTaskRemoved
应该与标志android:stopWithTask ="false"
一起触发。
我错过了什么吗?
请告诉我,在我需要添加一些可能很重要以找出问题所在的代码的情况下。
P.S.:我目前在4.2.2上进行了测试。
P.S.:我刚刚在4.1.2中测试了相同的代码,服务继续运行,我也在日志中收到了消息“ onTaskRemoved called”。
我该怎么做才能使其在所有版本上正常工作?
bindService()
方法启动的话,那么当客户端(例如Activity)解除绑定时,该服务会自动销毁,除非你还显式地调用了startService()
方法。 - matiashonStopService()
重新启动服务只有一种方法。 - Mehul Joisar