【发布时间】:2015-01-08 15:00:56
【问题描述】:
我有一个执行 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 调试时,我的应用程序可以完美运行。但是当拔掉电源时,服务似乎完全停止并且什么都不做。
【问题讨论】:
-
不相关,但可以用
// 1 minute is 60000 miliseconds代替developer.android.com/reference/android/text/format/… -
@njzk2 谢谢,这很有帮助。使用警报管理器做什么?这有什么帮助?
-
@njzk2 是正确的:
AlarmManager是要走的路,而不是这种循环AsyncTask:stackoverflow.com/a/14377875/603270 -
@shkschneider AsyncTask 是否进入睡眠状态/它可以被操作系统杀死吗?我需要它无限期地运行而不会中断。 AlarmManager 可以帮我做这个吗?
标签: java android android-intent android-asynctask android-service