String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
//挿入されている
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("SDカードが挿入されていません");
ad.setPositiveButton("OK", null);
ad.create();
ad.show();
}
端末自身の[設定]-[位置情報とセキュリティ]より、GPS機能がONに設定されているかを取得します。
OFFに設定されている場合にダイアログを表示して設定画面を呼び出す処理をしています。
// GPS機能設定の状態を取得
String GpsStatus = android.provider.Settings.Secure.getString(getContentResolver(), Secure.LOCATION_PROVIDERS_ALLOWED);
if (GpsStatus.indexOf("gps", 0) < 0) {
//GPSが無効だった場合
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("GPS機能がOFFになっています。\n設定画面を開きますか?");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//設定画面を呼び出す
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
ad.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
//何もしない
}
});
ad.create();
ad.show();
} else {
//GPSが有効だった場合
}
API Level3(Android 1.5)以降、セキュリティ上の問題で設定を強制的に変更することはできません。
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("メッセージ");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//肯定ボタンの操作
}
});
ad.setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//中立ボタンの動作
}
});
ad.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//キャンセルボタンの動作
}
});
ad.create();
ad.show();
キャンセルボタン等で何もせず、ダイアログを閉じるだけの場合はリスナーにnullを指定します。
ad.setNegativeButton("Cancel", null);
setViewで任意のViewを表示することも可能です。
続きを読む…»