如何在后台运行一个Android应用程序? [英] How to run an android app in background?
问题描述
这code将开机后系统自动运行一个应用程序,但应用程序会关闭pressing后退按钮后。
This code will run an app automatically after booting the system, but the app will close after pressing the back button.
如果该应用程序是通过点击它的图标,运行正常。即使在pressing后退按钮或运行其他应用程序,它会连续运行。
If the app is run normally by clicking it's icon. It will continuously run even after pressing the back button or running other apps.
public class AutoBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
我的问题是,如何使这个自动运行code连续运行,即使pressing后退按钮或运行其他应用程序?
My question is, how to make this auto run code to continuously run even after pressing the back button or running other apps?
推荐答案
您也许可以开始 服务
这里如果你想你的应用程序在后台运行。这是什么服务在Android中使用的 - 在后台运行,并做长期经营
You can probably start a Service
here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
UDPATE
您可以使用<一个href="http://developer.android.com/reference/android/app/Service.html#onStartCommand%28android.content.Intent,%20int,%20int%29"><$c$c>START_STICKY$c$c>使连续运行的服务。
You can use START_STICKY
to make your Service running continuously.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
这篇关于如何在后台运行一个Android应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!