我正在制作一个非常简单的应用程序,我希望其中的服务应该无限运行,就像 Whatsapp 服务在后台运行一样,即使该应用程序通过滑出从“最近的应用程序”中删除。
下面是我的代码。
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:
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:
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()));
}
}
最佳答案
在您的 Service#onStartCommand
方法中,将起始 Intent 存储到字段变量中,例如 mIntent
。
然后实现 Service#onTaskRemoved
方法,如下所示:
@Override
@TargetApi(14)
public void onTaskRemoved(Intent rootIntent) {
startService(mIntent);
}
关于java - 当应用程序从 Android 中最近的应用程序中滑出时,服务停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29268957/