【问题标题】:how to solve turning off Location如何解决关闭位置
【发布时间】:2017-03-18 20:50:03
【问题描述】:

我有以下脚本来使用 GoogleAPI 获取位置。在我的应用程序上工作是基于位置的。打开此 Activity 时,由于使用了 GoogleAPI,因此获得了称为纬度和经度的位置。

打开MainActivity时,如果在设备设置中打开Location。(Android智能手机)。Location知识是成功获取的,在MainActivity中不会发生任何问题。相反,当位置关闭时 我的 android 设备,当 Activity 启动时,我有错误并且应用程序关闭并显示一条名为“不幸的是应用程序已停止”的消息。

我该如何解决这个问题?而活动正在打开如何控制位置是否打开或关闭。

提前感谢您的帮助。

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
    , LocationListener , DialogInterface.OnClickListener {
public static final String KEY_LOC_ADD_URL = "http://xxxxxxxx/android_api/insertlocation.php";
public static final String KEY_LATITUDE = "enlem";
public static final String KEY_LONGITUDE = "boylam";
public static final String KEY_ID="id";

private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mevcutKonum;

private String[] seconds={"1","3","5","7","10"};
private String sonGuncellemeZamani;
private String employee_id;
private Long requestTime;

private TextView enlemTextView;
private TextView boylamTextView;
private TextView sonGuncellemeTextView;
private TextView employee_name;



private AlertDialog dialogSelectInternal;

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

    enlemTextView = (TextView) findViewById(R.id.enlem);
    boylamTextView = (TextView) findViewById(R.id.boylam);
    sonGuncellemeTextView = (TextView) findViewById(R.id.guncellemezamani);
    sonGuncellemeZamani = "";
    employee_name= (TextView) findViewById(R.id.userName);

    Intent intent = getIntent();
    employee_name.setText("Welcome User " +      intent.getStringExtra(Login_Activity.KEY_USERNAME));
    employee_id=intent.getStringExtra(Login_Activity.KEY_ID);


    buildGoogleApiClient();
    selectRequestTimeDialog();
    createLocationRequest();

}





protected void buildGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

protected void createLocationRequest() {
    locationRequest = LocationRequest.create()
            .setInterval(3000)
            .setFastestInterval(1000)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

protected void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            googleApiClient, locationRequest, this);
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}








private void updateUI() {


    if (mevcutKonum != null) {
        enlemTextView.setText(String.valueOf(mevcutKonum.getLatitude()));
        boylamTextView.setText(String.valueOf(mevcutKonum.getLongitude()));
        sonGuncellemeTextView.setText(sonGuncellemeZamani);
    }
}


@Override
protected void onResume() {
    super.onResume();
    googleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (googleApiClient.isConnected()) {
       stopLocationUpdates();
    }

    googleApiClient.disconnect();

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}




@Override
public void onConnected(@Nullable Bundle bundle) {
   if (mevcutKonum == null) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        mevcutKonum = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());

        try {
            addLocationToUser(String.valueOf(mevcutKonum.getLatitude()),String.valueOf(mevcutKonum.getLongitude()),employee_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        updateUI();


    }

    startLocationUpdates();

}



@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onLocationChanged(Location location) {
    mevcutKonum = location;
    sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
    updateUI();


}


private void addLocationToUser(final String latitude, final String longitude,final String id) throws JSONException {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, KEY_LOC_ADD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put(KEY_LATITUDE,latitude);
                params.put(KEY_LONGITUDE, longitude);
                params.put(KEY_ID,id);

                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }


private void selectRequestTimeDialog(){

    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setTitle("Konumunuzu Güncellemek istediğiniz zaman aralığını seçiniz");
    builder.setItems(seconds,this);
    builder.setNegativeButton("Cancel", null);
    dialogSelectInternal=builder.create();
    dialogSelectInternal.show();
}


@Override
public void onClick(DialogInterface dialog, int which) {


}

}

以上代码仅在位置开启时有效

【问题讨论】:

    标签: java android location


    【解决方案1】:

    在您的onCreate() 中,首先检查您的设备中是否启用了 GPS,如果是则创建位置更新,否则转到 位置设置

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                createLocationRequest();
            } else {
                Toast.makeText(this, "Please enable your gps first.", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent, 1);
            }
    

    在 GPS 上 -> 高精度选择:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            switch (requestCode) {
                case 1:
                    createLocationRequest();
                break;
            }
        }
    }
    

    希望这会有所帮助。

    【讨论】:

    • 感谢您的帮助,但我不明白。我是否必须使用您在代码上方和下方的每两种方法? @tahsinRupam
    • 第一个代码 sn-p 检查 gps 是否打开,如果是,则获取位置或转到设备的位置设置。第二个代码,如果选择 HIGH ACCURACY 则执行然后获取位置。希望这能解决问题。
    • 非常感谢您的关注。我会试试的
    • 不幸的是它不起作用。我需要其他解决方案。
    猜你喜欢
    • 2018-01-12
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多