如何在android中删除服务类中的位置更新?

前端之家收集整理的这篇文章主要介绍了如何在android中删除服务类中的位置更新?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个位置监听器类和一个服务类.在我的位置监听器课程中,我正在启动GPS,并且每隔10秒我就会继续获取该位置.我的要求是每天晚上7点停止GPS位置更新.我试图使用removeupdates停止服务中的GPS更新,但它无法正常工作.我怎样才能做到这一点.以下是我的代码.

LocationGPS.java

public class LocationGPS extends Activity implements  LocationListener {
@Override  
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
public static LocationManager locationManager;     
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10*1000,this);
Intent myIntent = new Intent(this,PIService.class);
            PendingIntent   sevenPMIntent = PendingIntent.getService(this,myIntent,0);

            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY,19);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0); 
            //alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,24*60*60*1000,sevenPMIntent);

}

@Override     
public void onLocationChanged(Location location) {      
                Toast.makeText(getApplicationContext(),"got new location",Toast.LENGTH_SHORT).show();

}    

@Override  
public void onProviderDisabled(String provider) {

}   

@Override
public void onProviderEnabled(String provider) {

}
@Override
public void onStatusChanged(String provider,int status,Bundle extras) {

}      
}

PIService.java

public class PIService extends Service{

@Override    
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub  
    return null;
}        
@Override     
public int onStartCommand (Intent intent,int flags,int startId)
{     
    super.onStartCommand(intent,flags,startId); 
    //Get the system current time.
    Date dt = new Date();
    int hours = dt.getHours();   

    //Compare the current time with 7PM 
    if(hours == 19){
        //if current time is 7PM
        Toast.makeText(getApplicationContext(),"Now the time is 7PM",Toast.LENGTH_LONG).show(); 
        LocationGPS.locationManager.removeUpdates(new LocationGPS()); //here is the place i am trying to remove the location updates.

    } 
    }


    return START_STICKY;      
}  

}

解决方法

public void onDestroy() {
    Log.e(TAG,"onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG,"fail to remove location listners,ignore",ex);
            }
        }
    }
}

猜你在找的Android相关文章