如果未启用GPS
,我将使用以下方法将用户带到设置页面。但它抛出异常 null
。
public void showSettingsAlert() {
try {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("Please enable GPS. 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();
} catch (Exception e) {
e.printStackTrace();
}
}
有人可以帮助我。
答案 0 :(得分:1)
使用以下行
AlertDialog alertDialog = alertDialogBuilder.create();
将此行添加到您的代码
public void showSettingsAlert() {
try {
AlertDialog.Builder alertDialogBuilder= new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("GPS Settings");
alertDialogBuilder
.setMessage("Please enable GPS. Do you want to go to settings menu?");
// On pressing Settings button
alertDialogBuilder.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();
}
});
//added this line
AlertDialog alertDialog = alertDialogBuilder.create();
// Showing Alert Message
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:1)
我认为你没有初始化变量 mContext 所以用当前的Activity初始化它,如 mContext = this;
答案 2 :(得分:0)
我找到了解决方案。关于这个问题的R& D表明从服务中调用AlertDialog不是一个好习惯。所以我正在创建一个主题为@android的新活动:style / Theme.DeviceDefault.Dialog作为Service的系统覆盖窗口,并点击该布局的OK按钮调用设置页面,代码如下。
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
this.startActivity(intent);
this.finish();
我正在从我的其他服务中调用此活动。
Intent intent;
intent = new Intent(this,
SettingsAlertActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);