檢測Gps和網絡定位權限

利用到GPS,用戶但願在手機GPS未開啓的時候,提醒用戶設置GPS開啓。

代碼以下android

 

 

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();
        }
   }ide

}ui

注意,必定要在AndroidManiFest.xml文件中註冊權限 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Android Location提供兩種獲取地理位置的方式:一種是GPS(LocationManager.GPS_PROVIDER),一種是Google網絡地圖(LocationManager.NETWORK_PROVIDER)
相關文章
相關標籤/搜索