如何解决关闭位置

时间:2017-03-18 20:50:03

标签: java android location

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

当打开MainActivity时,如果在设备设置中打开了位置。(Android智能手机)。位置知识是成功获取的,并且在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) {


}

}

只有在地点启用时,以上代码才有效

1 个答案:

答案 0 :(得分:0)

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上 - &gt;高精度选择:

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

希望这有帮助。