GPS定位

GPS定位

    • 主类
    • 效果图

主类

public class Demo extends AppCompatActivity {

    LocationManager manager;
    //权限数组
    String ss[];
    //标记位
    boolean isFlag = true;
    boolean isOk = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);

//权限数组赋值
        ss = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};

//获得位置信息管理类
        manager = (LocationManager) getSystemService(LOCATION_SERVICE);

//判断权限
        initPermission();

        if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            return;
        }

        
        
//方法调用        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
    }

    public  void  initPermission(){
    //遍历权限数组判断权限
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            for (int i = 0; i < ss.length; i++) {
                if(checkSelfPermission(ss[i]) != PackageManager.PERMISSION_DENIED){
                    isFlag = false;
                    break;
                }
            }
            if(!isFlag){
                requestPermissions(ss,100);
            }
        }
    }

//重写方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //判断值
        if(requestCode == 100){
            for (int i = 0; i < grantResults.length; i++) {
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    isOk = false;
                    break;
                }
            }
            if(isOk){
                Toast.makeText(this, "权限没成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            Toast.makeText(Demo.this, latitude+"", Toast.LENGTH_SHORT).show();//吐司纬度
            double longitude = location.getLongitude();
            Toast.makeText(Demo.this, longitude+"", Toast.LENGTH_SHORT).show();//吐司经度
            double altitude = location.getAltitude();
            Toast.makeText(Demo.this, altitude+"", Toast.LENGTH_SHORT).show();//吐司海拔
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};

}

效果图

GPS定位_第1张图片

你可能感兴趣的:(GPS定位)