1

我正在使用位置侦听器开发一个示例应用程序。我有 2 个 java 文件,一个是广播接收器,一个是活动。我的广播接收器本身就是一个位置监听器。在我的广播接收器中,我正在启动 gps 引擎并停止位置更新。我的要求是每天晚上 7 点停止位置更新。我正在尝试使用这段代码删除位置更新。

locationManager.removeUpdates(this); 

但它不起作用。我哪里出错了。下面是我的完整代码。

StopLLActivity.java

public class StopLLActivity extends Activity {
public static LocationManager lm;

@Override   
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent myIntent = new Intent( this, PIBroadCast.class); 
    PendingIntent   currentTime = PendingIntent.getBroadcast(this, 0, myIntent, 0);

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());

    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), currentTime);
    PendingIntent   sevenPMIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);

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

}

PIBroadCast.java

public class PIBroadCast extends BroadcastReceiver implements LocationListener{
public static LocationManager locationManager;  
public static boolean flagForGPS = false;
@Override  
public void onReceive(Context context, Intent intent) {

    locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); 
    if(flagForGPS == false){
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000 , 0 ,this);
        flagForGPS = true;
    }    

    //Get the system current time.
    Date dt = new Date();     
    int hours = dt.getHours();     

    //Compare the current time with 7PM and 5AM
    if(hours == 19){
        try {
            //if current time is 7PM
            Toast.makeText(context, "Now the time is 7PM", Toast.LENGTH_LONG).show(); 
            locationManager.removeUpdates(this); 
        } catch (Exception e) {

            e.printStackTrace();
        }


    }
}

@Override
public void onLocationChanged(Location location) {
    System.out.println("LOCATION IS : "+location);

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onProviderEnabled(String provider) {

}   

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

}

}
4

0 回答 0