如何解决关闭位置的问题



我有以下脚本来使用GoogleAPI获取位置。在"我的应用"上工作基于位置。当此活动被打开时,由于使用了GoogleAPI而获得了称为纬度和经度的位置。

打开

主活动时,如果在设备设置中打开位置。(安卓智能手机(。位置知识是一种成功的方式获得,并且在主活动中不会发生任何问题。相反,当位置信息关闭时我的安卓设备,当活动启动时,我有错误,应用程序关闭并显示一条名为"不幸的是应用程序已停止"的消息。

如何解决此问题? 当"活动"打开"如何控制位置是打开还是关闭"时。

提前感谢您的整个帮助。

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) {

}

}

上面的代码在位置仅打开时有效

在您的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;
        }
    }
}

希望这有帮助。

最新更新