12

簡潔でシンプル。アクティビティを開始し、電話で GPS モジュールが有効になっているかどうかを確認します。有効になっていない場合は、ユーザーにダイアログを表示して、手動で有効にするかどうかを尋ねます。[はい] で、場所の設定を有効にします。ユーザーは必要に応じて有効にできますが、ユーザーが何をしたかを確認する必要があります。

try {
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {}
if (isGPSEnabled) {
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
} else {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(
            "Your GPS module is disabled. Would you like to enable it ?")
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int id) {
                            // Sent user to GPS settings screen
                            final ComponentName toLaunch = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.SecuritySettings");
                            final Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            intent.setComponent(toLaunch);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivityForResult(intent, 1);
                            dialog.dismiss();
                        }
                    })
            .setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int id) {
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

コード内のロジックを続行するために、ユーザーが戻ってきたときに、場所の設定で何を選択したかを知る必要があります。基本的に、ユーザーが選択してアクティビティに戻るのを待ち、gps モジュールのステータスを再度確認する必要があります。

4

1 に答える 1

22

メソッドをチェックインLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)してみませんか?onActivityResult()ユーザーが戻ってきたら、を呼び出したため、このメソッドを呼び出す必要がありますstartActivityForResult()。ユーザーがGPSを有効にしている場合はisProviderEnabled()、別の結果が返されるはずです。

または、onResumeメソッドで常にGPSチェックを実行します。ユーザーが位置情報設定から戻ってGPSを有効にしていない場合、GPS有効になるまで同じプロンプトが表示されます。

それとも私は何かが足りないのですか?

于 2011-05-17T14:34:44.020 に答える