`

Android GPS开启与否检测

 
阅读更多
最近做一个项目:利用到GPS,用户希望在手机GPS未开启的时候,提醒用户设置GPS开启。

代码如下

 

public class GpsOpenorNot extends Activity {     @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {   // TODO Auto-generated method stub      if(requestCode==0){             }   super.onActivityResult(requestCode, resultCode, data);  }  /** Called when the activity is first created. */       @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         initGPS();         isGpsOpen();     }     public void  isGpsOpen(){      LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);      boolean GPS_status = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);//获得手机是不是设置了GPS开启状态true:gps开启,false:GPS未开启      boolean NETWORK_status = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);//另一种Gpsprovider(Google网路地图)      String status = "";      if(GPS_status){       status += "GPS开启";      }else{       status += "GPS未开启";       //return false;      }      if(NETWORK_status){       status += "NETWORK 开启";      }else{       status += "NETWORK 未开启";      }      //弹出对话框      new AlertDialog.Builder(GpsOpenorNot.this).setMessage(""+status).setPositiveButton("OK", null).show();      //弹出Toast      Toast.makeText(GpsOpenorNot.this, status, Toast.LENGTH_LONG).show();           }     private void initGPS(){         LocationManager locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        //判断GPS模块是否开启,如果没有则开启         if(!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)){          Toast.makeText(GpsOpenorNot.this, "GPS is not open,Please open it!", Toast.LENGTH_SHORT).show();          //转到手机设置界面,用户设置GPS          Intent intent=new Intent(Settings.ACTION_SECURITY_SETTINGS);          startActivityForResult(intent,0); //设置完成后返回到原来的界面         }         else {           //弹出Toast          Toast.makeText(GpsOpenorNot.this, "GPS is ready", Toast.LENGTH_LONG).show();           //弹出对话框          new AlertDialog.Builder(this).setMessage("GPS is ready").setPositiveButton("OK", null).show();         }    }

}

注意,一定要在AndroidManiFest.xml文件中注册权限 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Android Location提供两种获取地理位置的方式:一种是GPS(LocationManager.GPS_PROVIDER),一种是Google网络地图(LocationManager.NETWORK_PROVIDER)
来自:http://blog.163.com/lhl_soft/blog/static/20175000420121282495192/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics