发现我的服务在 Android 中是否正在运行?

发布于 2024-10-07 13:29:03 字数 182 浏览 0 评论 0原文

我有一项服务可以联系服务器以定期从我的应用程序传输一些数据。它工作正常。

但是当我重新启动(关闭然后打开)手机时,该服务无法重新启动。所以我的想法是,当用户重新启动手机后打开我的应用程序时再次启动该服务。为此,我必须知道我的服务是否正在运行?怎么办呢?

任何其他处理这种情况的想法也很感激。

提前致谢。

I have a service to contact the server to do some data transfer from my app periodically. Its working fine.

But when i restarted(switch off and on) my phone that service can not be restarted. so my idea is that to start that service again when the user open my app after restarting the phone. For that, i have to know about my service is running or not? how to do it?

Any other idea to handle this scenario also thankful.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葮薆情 2024-10-14 13:29:03

您需要 BroadcastReceiver 的实现,其中用于 BOOT_COMPLETED 操作。像这样:

public class OnStartReceiver extends BroadcastReceiver {


  @Override
  public void onReceive(Context context, Intent intent) {
//     your starting service code here
  }

}

另外,您应该添加 receiver< /a> 使用 android:name 标记到清单文件 = OnStartReceiver 的完全限定名称以及嵌套在 BOOT_COMPLETED 作为意图名称,如下所示:

<receiver android:name=".onStartReceiver">
   <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>                    
   </intent-filter>

you need an implementation of BroadcastReceiver, which is intended on BOOT_COMPLETED action. Like this:

public class OnStartReceiver extends BroadcastReceiver {


  @Override
  public void onReceive(Context context, Intent intent) {
//     your starting service code here
  }

}

Also, you should add receiver tag to your manifest file with android:name = your fully qualified name of OnStartReceiver and intent-filter tag nested with BOOT_COMPLETED as intent name, like this:

<receiver android:name=".onStartReceiver">
   <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED"/>                    
   </intent-filter>

骷髅 2024-10-14 13:29:03

创建一个 BroadcastReceiver 来侦听 ACTION_BOOT_COMPLETED 事件。更多详情请点击此处

Create a BroadcastReceiver to listen for the ACTION_BOOT_COMPLETED event. More details here.

绻影浮沉 2024-10-14 13:29:03

使用 AlarmManager 执行此类计划任务,因此您的服务不需要始终位于内存中。正如 Ribery 先生所指出的,使用 BroadcastReceiverACTION_BOOT_COMPLETED 在手机重启后重新安排任务。

Use AlarmManager for scheduled tasks like this, so your service does not need to be in memory all of the time. As Mr. Ribery indicates, use a BroadcastReceiver with ACTION_BOOT_COMPLETED to re-schedule your tasks after a phone reboot.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文