How to keep an Android app running indefinitely?

2020-02-08 19:09发布

问题:

I am writing an Android app which must always be running in the background until the user exits it from the app's menu. But now I notice that in Android after some time my app is stopped by itself without user intervention.

Any idea how to make sure my app will always be running in the background?

回答1:

You need to run a Service of your own. http://developer.android.com/reference/android/app/Service.html



回答2:

If you need to run at all times, look into a Service and startForeground. If you can let your Service die but get restarted, look into onStartCommand and START_STICKY.



回答3:

For your activity, in the manifest xml, put:

android:persistent="true"



回答4:

AndroidMainfest.xml looks like this with presistent=true:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="7" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" android:persistent="true">
        <activity
            android:name="com.example.test.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>
    </application>

</manifest>


回答5:

“While the app development documentation does explain the role of android:persistent, the use of that attribute is reserved for apps that are built within the AOSP.”

– Embedded Android