【问题标题】:IntentService starting new service - on which thread?IntentService 启动新服务 - 在哪个线程上?
【发布时间】:2014-07-11 15:53:03
【问题描述】:

我有一个维护 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;
}

}

【问题讨论】:

    标签: android multithreading intentservice


    【解决方案1】:

    服务始终运行其进程的 线程。运行 startService() 的线程充其量应该是无关紧要的(在最坏的情况下,它可能会产生问题,但不会使被调用的服务在该线程中运行)。

    (澄清一下:IntentService 也是如此——它只在后台线程上调用 onHandleIntent())。

    【讨论】:

    • 如果你说在主线程中运行可能会更清楚一点
    • 检查你的新服务是否是主线程: Looper.getMainLooper().getThread() == Thread.currentThread();或打印 id:Thread.currentThread().getId()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多