[英]Service stopped when app is swiped out from recent apps in Android
I am making a very simple app in which I want that a service should run infinitely just like Whatsapp service runs in background, even if the app is removed from Recent Apps by swiping out. 我正在制作一个非常简单的应用程序,在该应用程序中,我希望服务可以像Whatsapp服务在后台运行一样无限运行,即使该应用通过刷卡从“最近的应用程序”中删除也是如此。
Below is my code. 下面是我的代码。
AndroidManifest.xml: AndroidManifest.xml中:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.net.gs.servicetesting" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:process=":com">
<intent-filter>
<action
android:name="com.net.gs.servicetesting.MyService" />
</intent-filter>
</service>
</application>
</manifest>
MyService.java: MyService.java:
public class MyService extends Service {
private String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"Service Strated");
return START_STICKY;
}
@Override
public void onDestroy() {
Log.d(TAG,"Service Destoryed");
super.onDestroy();
}
}
MainActivity.java: MainActivity.java:
public class MainActivity extends ActionBarActivity {
String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Activity Strated");
startService(new Intent(MyService.class.getName()));
}
}
In your Service#onStartCommand
method store the starting intent to a field variable, let's say mIntent
. 在您的
Service#onStartCommand
方法中,将开始意图存储到字段变量中,比如说mIntent
。
Then implement the Service#onTaskRemoved
method like this: 然后像这样实现
Service#onTaskRemoved
方法:
@Override
@TargetApi(14)
public void onTaskRemoved(Intent rootIntent) {
startService(mIntent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.