IntentService启动新服务 - 在哪个线程?

时间:2014-07-11 15:53:04

标签: android multithreading intentservice

我有一个维护IntentService,它使用AlarmManager每30秒启动一次主服务。 我使用IntentService的原因是因为我希望我的MainService在后台线程上运行。

我的问题是 - 如果IntentService使用startService启动新服务(new Intent(this,MainService.class));,哪个线程是MainService的开头? IntentService的线程或UI线程?

这是我的代码:提前致谢!

/**
* A service that maintains all the required parts of Smoove alive. In case of a
* system startup or a crash of the main service, WatchDogService restarts the
* required service
*/
public class WatchDogService extends IntentService {

// Holds the alarm manager instance.
AlarmManager alarmMgr = null;


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

@Override
protected void onHandleIntent(Intent intent) {
    log.info("WatchDogService onHandleIntent");
    Intent intentMainService = new Intent(this, MainService.class);
    intentMainService.addFlags(Intent.FLAG_FROM_BACKGROUND);
    startService(intentMainService);

    }

    if(!isRegisteredToAlarmManager){
        alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        registerToAlarmManager();
    }
}

// Registers the service to the alarm manager. to start in every INTERVAK
// seconds.
private void registerToAlarmManager() {
    // Build the intent.
    log.info("entered registerToAlarmManager");
    Intent intent = new Intent(this.getApplicationContext(),WatchDogService.class);
    PendingIntent pendingIntent = PendingIntent.getService(
            this.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Pull the alarm manager service to register the service.
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0,
            INTERVAL * 1000, pendingIntent);

    isRegisteredToAlarmManager = true;
}

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

}

1 个答案:

答案 0 :(得分:3)

服务始终运行其流程的主题。运行startService()的线程最多应该是无关紧要的(最糟糕的是,它可能会产生问题,但不会使被调用的服务在该线程中运行)。

(只是为了澄清:IntentService也是如此 - 它只在后台线程上调用onHandleIntent()