android - 保持服务在后台运行,即使用户清除内存

标签 android android-service android-service-binding android-background android-backup-service

我有如下服务:

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/

相关文章:

android - 三星 "App optimisation"功能在 3 天后杀死后台应用程序

android - Android 中的本地服务绑定(bind) - 使用...还是不使用?

java - 如何删除支持库 (appcompat_v7) [Eclipse]

android - Gallery 类型已弃用

Android GCM 向服务器发送 token

android - 多个 IntentServices 并行运行

android - 当我的 Messenger 应用程序正在通话中或想要调用电话时,如何检测 skype/telegram/whatsapp 通话?

Android Activity 服务通信

Android SoundPool 在播放另一种声音之前不会第二次播放相同的声音

java - 无法解析 WifiManager 类中的公共(public)方法 setFrequencyBand