我是 android 新手,当手机被锁定时,我正试图从 onHandleIntent 的 gps 获取单个更新。这可能吗?
这是我的代码:
public class ActivityRecognitionService extends IntentService implements LocationListener {
private PowerManager.WakeLock mWakeLock;
public ActivityRecognitionService() {
super("ActivityRecognitionService");
}
@Override
protected void onHandleIntent(Intent intent)
{
if (ActivityRecognitionResult.hasResult(intent)) {
// Get the update
ActivityRecognitionResult result =
ActivityRecognitionResult.extractResult(intent);
// Get the most probable activity
DetectedActivity mostProbableActivity =
result.getMostProbableActivity();
int confidence = mostProbableActivity.getConfidence();
if(confidence>50)
{
int activityType = mostProbableActivity.getType();
checkIfGetPosition(activityType);
}
}
else {}
}
private void checkIfGetPosition(int activityType)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria lCriteria = new Criteria();
lCriteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
long lCurrentTime = System.currentTimeMillis()/MILLISECONDS_PER_SECOND;
lCurrentTime = lCurrentTime/SECOND_PER_MINUTE;
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
long lLastTime = 0;
if(lastLocation!=null)
lLastTime = lastLocation.getTime()/MILLISECONDS_PER_SECOND/SECOND_PER_MINUTE;
switch(activityType)
{
case DetectedActivity.IN_VEHICLE:
if(lCurrentTime > lLastTime+5)
{
aquireWakeLock();
locationManager.requestSingleUpdate(lCriteria, this, null);
}
break;
case DetectedActivity.ON_BICYCLE:
if(lCurrentTime > lLastTime+10)
{
aquireWakeLock();
locationManager.requestSingleUpdate(lCriteria, this, null);
}
break;
case DetectedActivity.ON_FOOT:
if(lCurrentTime > lLastTime+10)
{
aquireWakeLock();
locationManager.requestSingleUpdate(lCriteria, this, null);
}
break;
case DetectedActivity.UNKNOWN:
if(lCurrentTime > lLastTime+15)
{
aquireWakeLock();
locationManager.requestSingleUpdate(lCriteria, this, null);
}
break;
case DetectedActivity.STILL:
case DetectedActivity.TILTING:
if(lCurrentTime > lLastTime+60)
{
aquireWakeLock();
locationManager.requestSingleUpdate(lCriteria, this, null);
}
}
}
private void aquireWakeLock() {
final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
}
private void releaseWakeLock() {
if(mWakeLock==null) return;
else
{
mWakeLock.release();
mWakeLock = null;
}
}
@Override
public void onLocationChanged(Location location) {
if(location.getAccuracy()!=0.0 && location.getAccuracy()<100 )
{
releaseWakeLock();
}
}
@Override
public void onProviderDisabled(String provider) {
System.out.println("onProviderDisabled");
}
@Override
public void onProviderEnabled(String provider) {
System.out.println("onProviderEnabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
System.out.println("onStatusChanged: "+provider);
}
}
当我调试它时,它永远不会在 Listeners 方法中响应。