2011-05-17 31 views
11

簡單明瞭。我開始一個活動並檢查手機是否啓用了GPS模塊。如果未啓用,我會通過對話框提示用戶並詢問他是否要手動啓用它。在是的,我激活了「位置設置」。現在用戶可以啓用它,如果他想,但我需要檢查他做了什麼。檢查用戶是否在提示後啓用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模塊的狀態。

回答

19

爲什麼不在您的onActivityResult()方法中檢查LocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)?當用戶返回時,應調用此方法,因爲您稱爲startActivityForResult()。如果用戶已啓用GPS,則isProviderEnabled()現在應返回不同的結果。

另外,總是在你的onResume方法做GPS檢查。如果用戶從位置設置返回並且未啓用GPS,則他們將只收到相同的提示,直到啓用GPS

或者我錯過了什麼?

+0

隨着我上面寫的代碼,onActivityResults在啓動Settings intent後立即觸發...所以它不會等待用戶執行其操作。奇怪的行爲,但我用調試器看過它。 – Alin 2011-05-17 16:09:20

+0

奇怪地啓動設置意圖:\t startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),0); 正確地激活onActivityResult觸發器 – Alin 2011-05-17 16:42:51

+0

也許這是FLAG_ACTIVITY_NEW_TASK阻止了您所需的行爲。 – 2011-05-17 21:26:44

相關問題