生活随笔
收集整理的這篇文章主要介紹了
Android 监听手机GPS打开状态
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載請標明出處:http://blog.csdn.net/zhaoyanjun6/article/details/70854942
本文出自【趙彥軍的博客】
package com.yiba.core;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
/*** Created by ${zhaoyanjun} on 2017/3/29.* GPS 開關監聽*/public class GPS_Presenter {private Context mContext ;
private Receiver receiver ;
private GPS_Interface mInterface ;
private String GPS_ACTION =
"android.location.PROVIDERS_CHANGED" ;
public GPS_Presenter(Context context , GPS_Interface mInterface ){
this.mContext = context ;
this.mInterface = mInterface ;observeWifiSwitch();}
private void observeWifiSwitch(){IntentFilter filter =
new IntentFilter();filter.addAction( GPS_ACTION );receiver =
new Receiver() ;mContext.registerReceiver(receiver, filter);}
/*** 釋放資源*/public void onDestroy(){
if ( receiver !=
null ){mContext.unregisterReceiver( receiver );}
if (mContext!=
null){mContext =
null;}}class Receiver extends BroadcastReceiver {
@Overridepublic void onReceive(Context context, Intent intent) {
if (intent.getAction().matches( GPS_ACTION )) {
if ( mInterface !=
null ){mInterface.gpsSwitchState( gpsIsOpen( context ));}}}}
/*** 判斷GPS是否開啟,GPS或者AGPS開啟一個就認為是開啟的* @param context* @return true 表示開啟*/public boolean gpsIsOpen(
final Context context) {LocationManager locationManager= (LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps || network) {
return true;}
return false;}
}
package com.yiba.core;
/*** Created by ${zhaoyanjun} on 2017/3/29.* gps 開關監聽*/public interface GPS_Interface {void gpsSwitchState(
boolean gpsOpen );
}
package com.yiba.core;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements GPS_Interface {private GPS_Presenter gps_presenter ;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);gps_presenter =
new GPS_Presenter(
this ,
this ) ;}
@Overrideprotected void onDestroy() {
super.onDestroy();
if ( gps_presenter !=
null ){gps_presenter.onDestroy();}}
@Overridepublic void gpsSwitchState(
boolean gpsOpen) {
if ( gpsOpen ){Toast.makeText(
this,
" 手機GPS 打開", Toast.LENGTH_SHORT).show();}
else {Toast.makeText(
this,
" 手機GPS 關閉", Toast.LENGTH_SHORT).show();}}
}
總結
以上是生活随笔為你收集整理的Android 监听手机GPS打开状态的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。