我已经使用谷歌找到了解决方案,但我一无所获。 我有一个独立于活动运行的服务,但如果活动暂停/停止,则服务无法连接到Internet。 我使用一个线程来告诉我连接的状态,当活动回到前面时它可以正常工作。
对于IntentService,它也有同样的问题。
这是我的服务(收缩到重要部分):
public abstract class WakeAndRunService extends IntentService
{
public WakeAndRunService(String name)
{
super(name);
// TODO Auto-generated constructor stub
}
/** Has to return a notification that this Service will show when running */
protected abstract Notification setNotification();
/** will be called on onStartCommand to execute stuff*/
protected abstract void startStuff();
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
log("16", "-> WAR_Service: OnStartCommand ",1);
if(intent == null)
{
log("16", "WAR_Service: ####### ERROR: intent = null",1);
return 0;
}
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
alarmIntent = new Intent(this, TaskRun.class);
//Wichtig damit Service nicht nochmal ohne intent bei Main onDestroy(oder so) gestartet wird
return START_REDELIVER_INTENT;
}
//Notification setzen, welche auch wieder die Activity startet
private void showNotification()
{
notification = setNotification();
if(notification == null)
{
log("16", "WakeAndRunService ERROR: notification = null",1);
}
// Send the notification.
mNM.notify(notificationID, notification);
//wichtig, damit Service gestarted bleibt!!!!
startForeground(notificationID, notification);
}
public void startWakeAndRunService()
{
showNotification();
//alarmintent = TaskRun.class
alarmPendingIntent = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public static void stopWakeAndRunService()
{
cancelAlarm();
cancelNotification();
}
private static void cancelAlarm()
{
if(alarmMgr != null && alarmPendingIntent != null)
alarmMgr.cancel(alarmPendingIntent);
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onDestroy()
{
super.onDestroy();
log("16", "-> WAR_Service: onDestroy",1);
//TODO: check ob stopWakeAndRunService() hier hin?
}
}
服务以此开始:
sIntent = new Intent(this, LoadService.class);
pIntent = PendingIntent.getService(this, 0, sIntent, 0);
pIntent.send();