我使用以下方法将用户带到设置页面(如果未启用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();
}
}
有人可以帮我吗?
使用以下行
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();
}
}
我认为您没有初始化变量mContext。 所以用当前活动初始化它,如 mContext=this;
我找到了解决方案。关于此问题的研发表明,从服务调用 AlertDialog 不是一种好的做法。所以我正在创建一个主题为 @android:style/Theme.DeviceDefault.Dialog 的新活动作为服务中的系统覆盖窗口,并在单击该布局的"确定"按钮时使用以下代码调用设置页面。
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);