![](/img/trans.png)
[英]Where will code stop running when app is killed from task manager on Android
[英]Android service running in separately process kills when i swipe out application from task manager
我正在为Android开发一个应用程序。 而且我在Android服务方面遇到了一些麻烦。 我想让服务在后台运行并播放音频流。 但是不幸的是,当任务从活动管理器中滑出时,服务会重新启动。 对我来说很不方便,我希望该服务能够继续工作而不重启。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rkoptev.backgroundservice">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".TweetViewActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".TweetCollectorService"
android:process=":remote">
<intent-filter>
<action android:name="com.rkoptev.backgroundservice.TweetCollectorService"/>
</intent-filter>
</service>
</application>
</manifest>
TweetCollectorService.java
public class TweetCollectorService extends Service {
private static final String TAG = TweetCollectorService.class.getSimpleName();
private Timer timer;
private TimerTask updateTask = new TimerTask() {
@Override
public void run() {
Log.i(TAG, "Timer task doing work");
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
timer = new Timer("TweetCollectorTimer");
timer.schedule(updateTask, 1000);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
timer.cancel();
timer = null;
}
}
TweetViewActivity.java
public class TweetViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(TweetCollectorService.class.getName()));
}
}
有没有办法防止服务重启? 谢谢!
尝试将其添加到服务的onCreate
方法的底部:
Notification note = new Notification.Builder(this)
.setContentTitle("Notification title")
.setContentText("Notification message")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)).build();
startForeground(1, note);
这将告诉Android系统您不希望该服务被终止。
您还可以尝试从服务的onStartCommand()
方法返回Service.START_STICKY
,如下所述: https : onStartCommand()
刷卡等同于在应用程序上造成Force Stop
。 由于该服务仅是应用程序的一部分,因此也会停止。
或者,您可以执行以下操作:
noHistory="true"
在您的<activity>
标记中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.