如何让 Android 应用无限期运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3529834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep an Android app running indefinitely?
提问by perumal316
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.
我正在编写一个 Android 应用程序,该应用程序必须始终在后台运行,直到用户从应用程序菜单中退出为止。但现在我注意到在 Android 中,一段时间后我的应用程序在没有用户干预的情况下自行停止。
Any idea how to make sure my app will always be running in the background?
知道如何确保我的应用程序始终在后台运行吗?
回答by Konstantin Burov
You need to run a Service of your own. http://developer.android.com/reference/android/app/Service.html
您需要运行自己的服务。 http://developer.android.com/reference/android/app/Service.html
回答by Jake Basile
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
.
如果您需要一直运行,请查看 aService
和startForeground
。如果您可以让您的Service
死亡但重新启动,请查看onStartCommand
和START_STICKY
。
回答by Jake Basile
AndroidMainfest.xml looks like this with presistent=true:
AndroidMainfest.xml 看起来像这样,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>
回答by Kai Wang
“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
“虽然应用程序开发文档确实解释了 android:persistent 的作用,但该属性的使用是为在 AOSP 中构建的应用程序保留的。”
– 嵌入式安卓
回答by Someone Somewhere
For your activity, in the manifest xml, put:
对于您的活动,在清单 xml 中,输入:
android:persistent="true"
机器人:持久=“真”