Android业余爱好者,第一次在这里发帖。 我正在开发一个获取用户GPS位置的应用程序,然后发送到Mysql数据库。在Android 7.1(三星笔记5)上它运行得很好但是当我尝试在Android 4.2.2(三星J1)中使用时,该位置不会更新。
在我的MapsActivity.java下面
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
final int INTERVAL = 0; /* milliseconds */
final int DISTANCE = 0; /* meters */
//after asking the user for permission
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// to check if the request code is the same as we used, in this case 1
if (requestCode == 1) {
//if true, then it means we have the permission
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, DISTANCE, locationListener); //every 15 seconds or 50 meters
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
//change the title on action bar to have the name of the Bus
setTitle("Bus 1 - CMC");
mMap = googleMap;
//add Marker at VM Head Offices - as we waiting for the current location to be updated
LatLng maputo = new LatLng(-25.9758904,32.5805966);
mMap.addMarker(new MarkerOptions().position(maputo).title("Vodacom Head Office"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(maputo, 15));
//get the device location
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
isNetworkAvailable(MapsActivity.this);
//for better accuracy
int suitableMeter = 10; // adjust your need
if (location.hasAccuracy() && location.getAccuracy() <= suitableMeter) {
// This is your most accurate location.
//Updated last updated location time text
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
TextView textViewLocation = (TextView) findViewById(R.id.textViewLastUpdated);
textViewLocation.setText("Location last updated: " + currentDateTimeString);
LatLng busLocation = new LatLng(location.getLatitude(),location.getLongitude());
//TODO
//check if user has internet connection, if not then show dialog and ask to activate it
//send data to database
sendLocation(location.getLatitude(), location.getLongitude(), currentDateTimeString);
//clear the previous markers
mMap.clear();
mMap.addMarker(new MarkerOptions().position(busLocation).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(busLocation, mMap.getCameraPosition().zoom));
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
// Toast.makeText(MapsActivity.this, "GPS is available.", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.OUT_OF_SERVICE:
Toast.makeText(MapsActivity.this, "GPS is out of Service.", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Toast.makeText(MapsActivity.this, "GPS temporarily unavailable.", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MapsActivity.this, "Provider is enabled.", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
//TODO show dialog or pop up to open
Toast.makeText(MapsActivity.this, "Provider is disabled.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
//If device is running sdk<23 Marshmellow, no need to request permission
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, DISTANCE, locationListener);
} else {
// if don't have permission. ask for permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//ask for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
// we have permission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, DISTANCE, locationListener);
}
}
}
// To add the action bar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// Responding to Android Action Bar Events
@Override
public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) {
case R.id.editBusName:
Toast.makeText(this, "To create page", Toast.LENGTH_LONG).show();
return(true);
case R.id.reportBug:
Intent intent2 = new Intent(getApplicationContext(), ReportBug.class);
startActivity(intent2);
return(true);
case R.id.aboutApp:
Intent intent3 = new Intent(getApplicationContext(), AboutApp.class);
startActivity(intent3);
return(true);
case R.id.adminOptions:
Toast.makeText(this, "To create page", Toast.LENGTH_LONG).show();
return(true);
}
return(super.onOptionsItemSelected(item));
}
}