Java 从TimerTask-Android调用时,生成警报对话框导致异常

Java 从TimerTask-Android调用时,生成警报对话框导致异常,java,android,gps,android-alertdialog,Java,Android,Gps,Android Alertdialog,我的应用程序最初是在点击一个按钮时获得GPS坐标的 在我的活动中,我通过这种方式获得我的点击,一切正常: @Override public void onClick(View arg0) { // create class object gps = new GPSTracker(AndroidGPSTrackingActivity.this);

我的应用程序最初是在点击一个按钮时获得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是一项服务,如果未按以下方式设置网络和gps权限,它将实现LocationListener和showSettingAlert生成我的警报对话框

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,但当我尝试构建警报对话框时,我在这里得到一个空指针异常:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyApp.getContext());
MyApp扩展了应用程序,因为我需要到处都有上下文

我的问题似乎是,当我无法从timerTask实例化AlertDialog.Builder时,即使使用静态上下文也是如此。 如何解决? 导入android.app.Application

公共类MyApp扩展应用程序{ 私有静态MyApp mContext

@Override 
public void onCreate() {
    mContext= this;
    super.onCreate();
}

public static MyApp getContext() {
    return mContext;
    }
}

对于第一部分,我受此启发,将logcat错误粘贴到此处…尽管在Logc中提到错误的地方给出错误行,但实际上我已经提到了获取空指针异常AlertDialog.Builder AlertDialog=new AlertDialog.BuilderMyApp.getContext的点;我将在您使用MyApp.ge的服务中添加MyApp classintcontext?是的,在扩展服务和实现LocationListener的类中,我认为应该通过intent或构造函数将上下文传递给服务,然后在此服务中使用该上下文