如何使IntentService的线程保持活动状态?

时间:2012-07-28 10:40:37

标签: android multithreading intentservice

我正在编写一个跟踪用户位置的测试应用程序。我的想法是,我可以启动一项服务,然后注册位置更新。现在我正在使用IntentService。

服务代码(不起作用......)看起来像这样:

public class GpsGatheringService extends IntentService {

// vars
private static final String TAG = "GpsGatheringService";
private boolean stopThread;

// constructors
public GpsGatheringService() {
    super("GpsGatheringServiceThread");
    stopThread = false;
}

// methods
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand()");
    return super.onStartCommand(intent, flags, startId);
}

@Override
protected void onHandleIntent(Intent arg0) {
    // this is running in a dedicated thread
    Log.d(TAG, "onHandleIntent()");
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d(TAG, "onStatusChanged()");
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.d(TAG, "onProviderEnabled()");
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.d(TAG, "onProviderDisabled()");
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG, "onLocationChanged()");
        }
    };
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    while (!stopThread) {
        try {
            Log.d(TAG, "Going to sleep...");
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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

}

目前唯一发生的事情是“去睡觉......”的输出。我需要一些保持线程活动的机制(因为其他侦听器不再可用于状态更新)并且不会浪费cpu时间(我认为繁忙的循环不是首选方式)。 即使有很多其他方法如何实现应用程序行为(记录gps坐标),我也有兴趣通过这种方式解决这种方法来学习解决这种问题的技术!

2 个答案:

答案 0 :(得分:9)

  

如何让IntentService的线程保持活动状态?

你不是。您不会在这样的场景中使用IntentService

  

我需要一些保持线程活动的机制(因为其他的侦听器不再可用于状态更新)并且不会浪费cpu时间(我认为繁忙的循环不是首选方式)

不,在这种情况下,Service很好,因为您可以控制服务何时消失,您可以控制您创建的任何线程的生命周期等。IntentService不适合您的预期目的,因为 it 控制服务何时消失, it 控制线程的生命周期。

答案 1 :(得分:0)

考虑使用remote service。它对我有用。