Android 监听手机GPS打开状态实现代码
Android监听手机GPS打开状态实现代码
GPS_Presenter
packagecom.yiba.core;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.location.LocationManager;
/**
*Createdby${zhaoyanjun}on2017/3/29.
*GPS开关监听
*/
publicclassGPS_Presenter{
privateContextmContext;
privateReceiverreceiver;
privateGPS_InterfacemInterface;
privateStringGPS_ACTION="android.location.PROVIDERS_CHANGED";
publicGPS_Presenter(Contextcontext,GPS_InterfacemInterface){
this.mContext=context;
this.mInterface=mInterface;
observeWifiSwitch();
}
privatevoidobserveWifiSwitch(){
IntentFilterfilter=newIntentFilter();
filter.addAction(GPS_ACTION);
receiver=newReceiver();
mContext.registerReceiver(receiver,filter);
}
/**
*释放资源
*/
publicvoidonDestroy(){
if(receiver!=null){
mContext.unregisterReceiver(receiver);
}
if(mContext!=null){
mContext=null;
}
}
classReceiverextendsBroadcastReceiver{
@Override
publicvoidonReceive(Contextcontext,Intentintent){
if(intent.getAction().matches(GPS_ACTION)){
if(mInterface!=null){
mInterface.gpsSwitchState(gpsIsOpen(context));
}
}
}
}
/**
*判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的
*@paramcontext
*@returntrue表示开启
*/
publicbooleangpsIsOpen(finalContextcontext){
LocationManagerlocationManager
=(LocationManager)context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)
booleangps=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)
booleannetwork=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gps||network){
returntrue;
}
returnfalse;
}
}
GPS_Interface回调接口
packagecom.yiba.core;
/**
*Createdby${zhaoyanjun}on2017/3/29.
*gps开关监听
*/
publicinterfaceGPS_Interface{
voidgpsSwitchState(booleangpsOpen);
}
在Activity中使用
packagecom.yiba.core;
importandroid.os.Bundle;
importandroid.support.v7.app.AppCompatActivity;
importandroid.widget.Toast;
publicclassMainActivityextendsAppCompatActivityimplementsGPS_Interface{
privateGPS_Presentergps_presenter;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps_presenter=newGPS_Presenter(this,this);
}
@Override
protectedvoidonDestroy(){
super.onDestroy();
//释放资源
if(gps_presenter!=null){
gps_presenter.onDestroy();
}
}
@Override
publicvoidgpsSwitchState(booleangpsOpen){
if(gpsOpen){
Toast.makeText(this,"手机GPS打开",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"手机GPS关闭",Toast.LENGTH_SHORT).show();
}
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!