Android--监听GPS开启和关闭

关键代码如下

?
1
2
3
4
5
getContentResolver()
             .registerContentObserver(
                     Settings.Secure
                             .getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED),
                     false , mGpsMonitor);

完整的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MyActivity  extends Activity {
 
     private final ContentObserver mGpsMonitor =  new ContentObserver( null ) {
         @Override
         public void onChange( boolean selfChange) {
             super .onChange(selfChange);
 
             boolean enabled = mLocationManager
                     .isProviderEnabled(LocationManager.GPS_PROVIDER);
            Log.i ( "gps : " + enabled);
         }
     };
 
     private LocationManager mLocationManager;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
     }
 
     protected void onStart() {
         getContentResolver()
                 .registerContentObserver(
                         Settings.Secure
                                 .getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED),
                         false , mGpsMonitor);
     };
 
     @Override
     protected void onStop() {
         super .onStop();
         getContentResolver().unregisterContentObserver(mGpsMonitor);
     }
}

你可能感兴趣的:(Android--监听GPS开启和关闭)