我正在创建一个需要位置权限才能运行的应用程序,在弹出权限对话框后,我的应用程序开始显示我的应用程序的用户界面,但是当我点击GO按钮时,该按钮不会回应我的行动,只是坐在那里什么都不做,直到我重新启动我的应用程序,一切都开始正常工作,我的按钮开始再次响应。
这是我的活动:
以下是我的活动代码:
public class ParStuActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_par_stu);
dcounter = 0;
searchbtn = (Button) findViewById(R.id.searchbtn);
searchedt2 = (EditText) findViewById(R.id.searchpar);
autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
buildGoogleApiClient();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.maps);
mapFragment.getMapAsync(this);
geocoder = new Geocoder(this, Locale.getDefault());
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}else{
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000, 10, this);
}
searchbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
url = "https://www.tuitionathome.my/inc/myMobileDL.php?Operation=getTutors&lat=" + lat + "&lng=" + lng + "&search=" + searchedt2.getText().toString();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.maps);
mapFragment.getMapAsync(ParStuActivity.this);
// Creating volley request obj
maps.clear();
pDialog = new ProgressDialog(ParStuActivity.this);
pDialog.setMessage("Hold On....");
pDialog.show();
pDialog.setCancelable(false);
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url,
null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("Respond : ", response.toString());
pDialog.dismiss();
int totalRecords = 1;
// Parsing json
for (int i = -1; i < totalRecords; i++) {
try {
final int i2 = 0;
JSONArray obj = response.getJSONArray("dataTable");
JSONObject jsonObject = obj.getJSONObject(i);
final String markerurl = jsonObject.getString("iconPath");
double lat3 = jsonObject.getDouble("lat");
double lng3 = jsonObject.getDouble("lng");
final String title = jsonObject.getString("userName");
final String subtitle = jsonObject.getString("address");
final LatLng sydney = new LatLng(lat3, lng3);
if (markerurl.contains("null")) {
maps.addMarker(new MarkerOptions()
.title(title)
.snippet(subtitle)
.position(sydney));
} else {
final Bitmap[] bmp = new Bitmap[1];
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
URL url;
try {
url = new URL(markerurl);
bmp[0] = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = maps.addMarker(new MarkerOptions()
.position(sydney)
.title(title)
.snippet(subtitle)
.icon(BitmapDescriptorFactory.fromBitmap(bmp[0].createScaledBitmap(bmp[0], 100, 100, false))));
mHashMap.put(marker, i2);
}
});
}
});
thread.start();
}
totalRecords = Integer.valueOf(response.getString("recordsTotal"));
Log.i("Total records", response.getString("recordsTotal"));
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
new AlertDialog.Builder(ParStuActivity.this)
.setTitle("Error")
.setMessage("Internet connection error")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
});
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
String placeDetailsStr = place.getName() + "\n"
+ place.getId() + "\n"
+ place.getLatLng().toString() + "\n"
+ place.getAddress() + "\n"
+ place.getAttributions();
System.out.print("Place: " + place.getName() + placeDetailsStr);
lat = String.valueOf(place.getLatLng().latitude);
lng = String.valueOf(place.getLatLng().longitude);
try {
addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
//String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return;
} else {
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
autocompleteFragment.setText(city);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ParStuActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("cityname", city);
editor.putString("lat", lat);
editor.putString("lng", lng);
editor.apply();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.maps);
mapFragment.getMapAsync(ParStuActivity.this);
}
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
System.out.print("An erroe occured " + status);
}
});
}
@Override
public void onMapReady(final GoogleMap map) {
if (lat == null && lng == null) {
System.out.print("location null");
} else {
double latd = Double.parseDouble(lat);
double lngd = Double.parseDouble(lng);
LatLng testloc = new LatLng(latd, lngd);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(testloc, 13));
}
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
final String username = marker.getTitle();
final double lat2 = marker.getPosition().latitude;
final double lng2 = marker.getPosition().longitude;
url23 = "https://www.tuitionathome.my/inc/myMobileDL.php?Operation=getTutors&lat=" + lat2 + "&lng=" + lng2 + "&search=" + username.replace(" ", "%20");
Log.i("URL23", url23);
Log.i("Lat", String.valueOf(lat2));
Log.i("lng", String.valueOf(lng2));
// Creating volley request obj
pDialog = new ProgressDialog(ParStuActivity.this);
pDialog.setMessage("Hold On....");
pDialog.show();
pDialog.setCancelable(false);
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url23,
null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("respond test length", response.toString());
pDialog.dismiss();
Intent intent = new Intent(ParStuActivity.this, TutorView.class);
startActivity(intent);
// Parsing json
for (int i = 0; i < 1; i++) {
try {
JSONArray obj = response.getJSONArray("dataTable");
JSONObject jsonObject = obj.getJSONObject(i);
String ttID = jsonObject.getString("recId");
Log.i("ttID test", ttID);
Log.i("lat", String.valueOf(lat2));
Log.i("lng", String.valueOf(lng2));
Log.i("USERNAME", username.toString());
LatLng distanceloc = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
LatLng markerloc = new LatLng(lat2, lng2);
CalculationByDistance(distanceloc, markerloc);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ParStuActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("TTID", ttID);
editor.putString("itemname", username.toString());
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
new AlertDialog.Builder(ParStuActivity.this)
.setTitle("Error")
.setMessage("Internet connection error")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
});
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
if (ContextCompat.checkSelfPermission(ParStuActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(ParStuActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
ActivityCompat.requestPermissions(ParStuActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
2);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(ParStuActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
2);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
map.setMyLocationEnabled(true);
}
maps = map;
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 2: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.maps);
mapFragment.getMapAsync(ParStuActivity.this);
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
} else {
maps.setMyLocationEnabled(true);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
alatitude = mLastLocation.getLatitude();
alongitude = mLastLocation.getLongitude();
LatLng aloc = new LatLng(alatitude, alongitude);
maps.animateCamera(CameraUpdateFactory.newLatLngZoom(aloc, 13));
}
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(ParStuActivity.this, "Permission access to current locarion denied", Toast.LENGTH_LONG).show();
}
break;
}
}
// other 'case' lines to check for other
// permissions this app might request
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationManager locManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locManager.getBestProvider(crit, true);
if (ContextCompat.checkSelfPermission(ParStuActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
} else {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 10, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
alatitude = mLastLocation.getLatitude();
alongitude = mLastLocation.getLongitude();
lat = String.valueOf(mLastLocation.getLatitude());
lng = String.valueOf(mLastLocation.getLongitude());
}
}
if (dcounter == 0) {
if (ContextCompat.checkSelfPermission(ParStuActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
} else {
dcounter++;
LatLng aloc = new LatLng(alatitude, alongitude);
maps.animateCamera(CameraUpdateFactory.newLatLngZoom(aloc, 13));
try {
addresses = geocoder.getFromLocation(alatitude, alongitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
//String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return;
} else {
String city = addresses.get(0).getLocality();
autocompleteFragment.setText(city);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ParStuActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("cityname", city);
editor.putString("lat", lat);
editor.putString("lng", lng);
editor.apply();
}
}
} else {
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
alatitude = location.getLatitude();
alongitude = location.getLongitude();
lng = String.valueOf(location.getLongitude());
lat = String.valueOf(location.getLatitude());
try {
addresses = geocoder.getFromLocation(alatitude, alongitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
//String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return;
} else {
String city = addresses.get(0).getLocality();
autocompleteFragment.setText(city);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ParStuActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("cityname", city);
editor.putString("lat", lat);
editor.putString("lng", lng);
editor.apply();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
}