gpt4 book ai didi

java - 我的 Android 服务无法继续运行

转载 作者:行者123 更新时间:2023-12-02 05:05:23 25 4
gpt4 key购买 nike

我有一个执行 AsyncTask 的服务,该服务在每次完成后调用自身。正如您将在下面看到的,我正在前台启动我的服务。当我将其插入计算机并将输出输出到 LogCat 时,它会成功启动并继续按预期运行。我知道这一点是因为为了测试,我让 AsyncTask 循环每 5 分钟发出一个通知。但是,当我将其从计算机上拔下时,通知不会出现!就好像服务在我启动后就完全停止了!

注意:我的服务是常规服务,而不是 IntentService。

这是我的 onStartCommand...

@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
getData(intent);
self = this;

// Enter foreground state
String title = "Service started.";
String subject = "Service is running.";
String body = "Monitoring...";
Notification notification = new Notification(R.drawable.ic_launcher, title,
System.currentTimeMillis());
if(notificationSounds)
notification.defaults |= Notification.DEFAULT_SOUND;
else
notification.sound = null;
Intent notificationIntent = new Intent(this, MainActivity3.class);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, subject, body, pendIntent);
startForeground(1500, notification);

new BatteryLifeTask(appContext).execute();
return START_NOT_STICKY;
}

这是我的异步任务:

// Looping AsyncTask for continuous mode
private class BatteryLifeTask extends AsyncTask<Void, Void, Void> {

// Member variables
Context appContext;
int batteryPct0;

public BatteryLifeTask(Context context) {
super();
appContext = context;
}

protected Void doInBackground(Void... params) {
System.out.println("Entering doInBackground");
// Get the initial battery level
batteryPct0 = getBatteryPercent();
System.out.println("Initial battery percent: " + batteryPct0);

// Check time
Calendar c = Calendar.getInstance();
Date dateNow = c.getTime();
// getTime returns ms, need minutes. 60000ms in a minute.
long currTime = dateNow.getTime() / 60000;

if(currTime >= timeToUse){
finished = true;
stopSelf();
}

System.out.println("Leaving doInBackground");
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(!finished) {
int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds
System.out.println("Entering postExecute. waitTime is " + waitTime);
Runnable r = new Runnable() {
@Override
public void run() {
if(!finished) { // In case postDelayed is pending, avoids extra notification
System.out.println("An interval has passed.");
calculateHelper(batteryPct0);
new BatteryLifeTask(appContext).execute();
}
}
};
Handler h = new Handler();
h.postDelayed(r, waitTime);
}
}
}

这是我用于创建通知的代码:

// Method for creating a notification
@SuppressWarnings("deprecation")
void notify0(int id, String title, String subject, String body, boolean playSound){
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification(android.R.drawable.
PendingIntent pending = PendingIntent.getActivity(
getApplicationContext(), 0, new Intent(), 0);
notify.setLatestEventInfo(getApplicationContext(), subject, body, pending);
if(playSound)
notify.defaults |= Notification.DEFAULT_SOUND;
else
notify.sound = null;

// Cancel running notification if exists
NM.cancel(id);

// Push notification
NM.notify(id, notify);
}



谁能帮我?这让我发疯!我的应用程序在插入并连接到 USB 调试时运行完美。但是当拔掉插头时,该服务似乎完全停止并且不执行任何操作。

最佳答案

这是因为您要返回 START_NOT_STICKY关于服务的onStartCommand() .

START_NOT_STICKY if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent).

您应该返回START_STICKY相反

START_STICKY If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service.

检查这个service api changes特别是服务生命周期部分发生了变化。

关于java - 我的 Android 服务无法继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27843070/

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