我有一个应用程序,通过短信在固定时间后发送GPS坐标。它工作正常,但现在当我运行时它在发射时崩溃,我的设备上的GPS图标闪烁,永远不会稳定。我不知道问题出在GPS系统中,或者我的应用程序或设备出现了问题。我已在清单文件中添加了所有权限。
主要活动代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startLocationTracking();
}
private void startLocationTracking()
{
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1=new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(MainActivity.this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("exjfkd"+e);
}
Calendar cal=Calendar.getInstance();
cal.add(Calendar.SECOND,5);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10, sender1);
System.out.println("start timer");
}
}
接收器类代码
public class AlarmReceiver extends BroadcastReceiver{
long time = 10 * 1000;
long distance = 10;
@SuppressLint("NewApi")
@Override
public void onReceive(final Context context, Intent intent) {
System.out.println("alarm receiver....");
LocationManager locationManager = (LocationManager)context
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, time,
distance, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
String phoneNo = "+994580556";
String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, Text, null, null);
Log.i("Send SMS", "");
Toast.makeText(context, "message sent", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
LocationListener locationListener = new LocationListener() {
@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 onLocationChanged(Location location) {
}
};
}
我的第二个问题是,如果找不到GPS,我怎么能防止它崩溃。
logcat的
10-15 17:26:27.745: E/AndroidRuntime(5018): FATAL EXCEPTION: main
10-15 17:26:27.745: E/AndroidRuntime(5018): java.lang.RuntimeException: Unable to start receiver com.example.locationupdates.AlarmReceiver: java.lang.NullPointerException
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2565)
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.app.ActivityThread.access$1500(ActivityThread.java:165)
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.os.Handler.dispatchMessage(Handler.java:107)
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.os.Looper.loop(Looper.java:194)
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.app.ActivityThread.main(ActivityThread.java:5370)
10-15 17:26:27.745: E/AndroidRuntime(5018): at java.lang.reflect.Method.invokeNative(Native Method)
10-15 17:26:27.745: E/AndroidRuntime(5018): at java.lang.reflect.Method.invoke(Method.java:525)
10-15 17:26:27.745: E/AndroidRuntime(5018): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
10-15 17:26:27.745: E/AndroidRuntime(5018): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
10-15 17:26:27.745: E/AndroidRuntime(5018): at dalvik.system.NativeStart.main(Native Method)
10-15 17:26:27.745: E/AndroidRuntime(5018): Caused by: java.lang.NullPointerException
10-15 17:26:27.745: E/AndroidRuntime(5018): at com.example.locationupdates.AlarmReceiver.onReceive(AlarmReceiver.java:55)
10-15 17:26:27.745: E/AndroidRuntime(5018): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2558)
10-15 17:26:27.745: E/AndroidRuntime(5018): ... 10 more
答案 0 :(得分:1)
来自LocationManager.getLastKnownLocation documentation:
返回提供程序的最后已知位置,或null。
所以你应该检查是否返回了null。如果没有最后的已知位置,显然会返回null。
答案 1 :(得分:0)
首先,您应该检查设备中是否有GPS可用,因为如果设备有A-GPS,则GLONASS然后locationManager.getProvider(LocationManager.GPS_PROVIDER)
将返回null,然后您必须使用LocationManager.NETWORK_PROVIDER
来获取来自您的网络/ Wifi的位置。
这可能是你的第二个问题的答案:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getProvider(LocationManager.GPS_PROVIDER) == null) {
Log.v(TAG, "GPS not available");
}
else
{
Log.v(TAG, "GPS available");
}
使用此。它将从GPS或网络提供位置:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}