gpt4 book ai didi

java - 检查启动时启动的 IntentService 是否仍在运行

转载 作者:行者123 更新时间:2023-11-30 02:45:57 25 4
gpt4 key购买 nike

进入 list :

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

进入应用:

<service android:name="Myservice"/>
<receiver android:name="com.myapp.Onstart"> <!-- Tested also only .Onstart -->
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

启动.java:

package com.myapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class Onstart extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
context.startService(new Intent(context, Myservice.class));
}
}
}

我的服务.java:

package com.myapp;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class Myservice extends IntentService
{

public Myservice() {
super("Myservice");
}

@Override
protected void onHandleIntent(Intent intent) {
int n=0;
while(true)
{
if (i==20) {
stopSelf();
}
i = i++;
Log.i("Test", "n."+n++);
try {
Thread.sleep(10000);
}
catch (InterruptedException e)
{ }
}
}

}

手动启动应用程序会显示 Main.java,我想知道那里(在 Main.java 中)我的 IntentService Myservice 是否仍在运行。怎么做?

最佳答案

虽然我知道您的问题是它是否正在运行,但我不明白您为什么需要知道。由于 IntentService 按需工作。

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

此外,从 Context.startService(Intent) 调用文档:

If the service is being started or is already running, the ComponentName of the actual service that was started is returned; else if the service does not exist null is returned.

如果必须的话,可以检查startService(Intent)的返回参数。

编辑:您似乎需要一个完全由您处理的启动服务,而不是系统。这将允许您拥有自己的停止条件。请引用ServicesServices Guide关于如何使用它们。

引用资料:
IntentService
startService(Intent service)
Services
Services Guide

关于java - 检查启动时启动的 IntentService 是否仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25027052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com