我的应用程序最初在点击一个按钮时获得了GPS坐标。
在我的活动中,我以这种方式点击(一切正常):
@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
GPSTracker是服务,它实现了LocationListener和showSettingAlert()构建我的警报对话框(如果未设置网络和gps权限),如下所示
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();
}
现在我需要每分钟都这样做,所以我包含了一个timerTask但是当我尝试构建我的Alert对话框时,我在这里得到一个空指针异常:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyApp.getContext());
MyApp扩展了应用程序,因为我需要在任何地方都有上下文。
import android.app.Application;
公共类MyApp扩展Application { private static MyApp mContext;
@Override
public void onCreate() {
mContext= this;
super.onCreate();
}
public static MyApp getContext() {
return mContext;
}
}
对于第一部分,我受到code
的启发