0

创建了IntentService并将for loop放入onHandleIntent方法中。每当我关闭应用程序(从最近不强制关闭),它停止。但onDestroy没有叫。 我也尝试过不同的设备。我不认为这是一个内存不足的问题。
服务的意思是只有当应用程序在前台使用?
我必须在主线程的背景中执行一些任务,并且在用户关闭应用程序时服务已关闭。
这里是我的示例代码Android服务在关闭应用程序后立即停止

public class MyIntentService extends IntentService { 


    private static final String TAG = "MyIntentService"; 

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


    @Override 
    protected void onHandleIntent(Intent intent) { 

     for (int i = 0; i < 30; i++) { 
      Log.d(TAG, "onHandleIntent: " + i); 
      try { 
       Thread.sleep(600); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 


    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Log.d(TAG, "onDestroy: "); 
    } 
} 

裁判:How to keep an IntentService running even when app is closed?
Service restarted on Application Close - START_STICKY

回答

1

使用下面的重启服务代码上述方法关闭App

public class MyService extends Service { 

@Override 
public int onStartCommand(final Intent intent, final int flags, 
          final int startId) { 
    super.onStartCommand(intent, flags, startId); 
    return Service.START_STICKY; 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onTaskRemoved(Intent rootIntent) { 
    Intent restartService = new Intent(getApplicationContext(), 
      this.getClass()); 
    restartService.setPackage(getPackageName()); 
    PendingIntent restartServicePI = PendingIntent.getService(
      getApplicationContext(), 1, restartService, 
      PendingIntent.FLAG_ONE_SHOT); 
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 100, restartServicePI); 
    Toast.makeText(this, "onTaskRemoved", Toast.LENGTH_SHORT).show(); 
    super.onTaskRemoved(rootIntent); 
}} 

后100毫秒后onTaskRemoved重新启动服务。

+0

为什么我应该使用onTaskRemoved。除非记忆力下降,否则服务不应该被杀死。根据Android文档,这是默认功能。 –

0
@Override 
    public void onTaskRemoved(Intent rootIntent) { 
} 

上述方法将在应用程序从最近删除时调用。但是没有上下文。所以你需要在上下文可用时完成你的任务。因此,地方的代码里面,

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    //do your operations 
    return START_REDELIVER_INTENT; 
} 

记住里面onStartCommand你应该返回要么START_REDELIVER_INTENT或START_STICKY。你可以得到不同的结果from here.

还有一件事,只有在代码的任何地方调用startService时,onStartCommand才会自动撤销。

所以,通过调用

startService(new Intent(context, serviceName.class));

按照上面的代码onStartCommand如果服务没有停止将定期撤销运行服务。

+0

为什么我应该使用onTaskRemoved。除非记忆力下降,否则服务不应该被杀死。根据Android文档,这是默认功能。 –

+0

这里是一个解释 - https://stackoverflow.com/questions/20392139/close-the-service-when-remove-the-app-via-swipe-in​​-android?rq=1 – Exigente05

相关问题