【问题标题】:How to launch service on boot complete android?如何在启动完整的 android 上启动服务?
【发布时间】:2015-05-07 02:19:59
【问题描述】:

我已经阅读了一些关于启动服务的教程。 我所做的是:

在清单中:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" >
</uses-permission>

<receiver android:name="my.package.ServiceStartup" >
   <intent-filter>
       <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
</receiver>

代码:

public class ServiceStartup extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
           @Override
           public void run() {
               Intent dialogIntent = new Intent(getBaseContext(), MyActivity.class);
               dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               getApplication().startActivity(dialogIntent);
           }
        }, 10000);
    }
}

这样,如果我重新启动设备并转到活动应用程序中的设置,我的服务不会启动。我能做些什么?我在哪里出错?谢谢!!

【问题讨论】:

标签: android service boot application-restart


【解决方案1】:

您想开始活动或服务。如需服务,您必须致电startService()。喜欢:

getApplication().startService(new Intent(this, MyService.class));

【讨论】:

  • 我想启动服务“ServiceStartup”,它会在 10 秒后启动一个活动......
  • 我假设你在这 10 秒内没有做太多事情。至少没有得到用户输入。您可能想致电Thread.sleep(10000),然后开始活动。否则在你的 onCreate() 活动中,你将不得不等待 10 秒,然后从那里开始。
  • 好的.. 但我不认为问题出在我的活动应用程序中(在设置上)我没有看到我的服务正在运行
  • 因为你还没有启动它。您只是开始了活动。如果您想了解更多信息,请将您的活动代码粘贴到您开始活动的位置。
  • 女巫服务我必须在 postDelayed 开始? :)
【解决方案2】:

您是否运行了您的应用程序?参考this tutorial

如果您的应用程序安装在 SD 卡上,那么它在 android.intent.action.BOOT_COMPLETED 事件之后不可用。在这种情况下为 android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 事件注册自己。


另请注意,从 Android 3.0 开始,用户需要至少启动一次应用程序才能接收 android.intent.action.BOOT_COMPLETED 事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多