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

fli*_*liX 5 multithreading android 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;
}
Run Code Online (Sandbox Code Playgroud)

}

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

Com*_*are 9

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

你没有.你没有IntentService在这样的场景中使用.

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

不,在这种情况下Service是好的,因为你控制服务时会消失,你控制你创建的线程的寿命等IntentService是不适合你的预期目的,因为当服务消失控制和控制线程的生命周期.