我的应用在关闭位置服务时崩溃了。它给出了NullPointerException。我添加了粗略和精细位置的权限。现在我该如何处理?我想处理此异常并向用户提供“位置服务已关闭。请启用位置服务”的祝酒词。如果有人知道,请帮助。下面是我的代码。
package com.bddevs.ddbllocator;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (googleMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
googleMap.setMyLocationEnabled(true);
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = LocationManager.NETWORK_PROVIDER;
Location myLocation = locationmanager.getLastKnownLocation(provider);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
LatLng latlng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
如果可以,请帮忙。