我有如下服务:
public class service extends Service
{
private static final String TAG = "MyService";
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Intent intents = new Intent(getBaseContext(),MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
return START_NOT_STICKY;
}
}
它运行良好,当我进入应用程序设置时,我可以检查服务是否正在运行。但是,如果我通过长按主页按钮清除所有应用程序并清除它们。我没有看到我正在运行的服务。如何保持我的服务在后台运行,即使用户清除了应用程序或内存?谢谢大家
这是我的 list
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hellobootservice"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true"
android:process=":hello"
android:name=".service" />
</application>
</manifest>
最佳答案
替换
return START_NOT_STICKY;
与
return START_STICKY;
在 onStartCommand() 中。
关于android - 保持服务在后台运行,即使用户清除内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39636994/