2014-07-24 33 views
0

我希望我的應用程序只有在打開GPS時才能運行,以下是我迄今爲止所做的活動。如何禁用Android中AlertDialog的所有其他操作?

private LocationManager locationManager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    setUpMapIfNeeded(); 

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    checkForGPS(); 
} 

private void checkForGPS(){ 
    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); 
    alertDialog.setTitle(getResources().getString(R.string.gps_error_title)); 
    alertDialog.setMessage(getResources().getString(R.string.gps_error_message)); 
    alertDialog.setButton(getResources().getString(R.string.alert_button_turn_on), new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); 
     } 
    }); 
    if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
     alertDialog.show(); 
    } 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    checkForGPS(); 
} 

現在我有這個對話框的問題,因爲它工作正常,但我能夠按下我的後退按鈕,只是忽略它。我怎麼解決這個問題?

+0

檢查此問題http://stackoverflow.com/questions/22627663/android-alertdialog-user-click-somewhere-else/22627698#22627698 –

+0

你是什麼意思,因爲它工作正常,但我能夠按我的後退按鈕,只是忽略它。「? – Setu

+0

@Setu我的意思是它做它必須做的事情,它的按鈕) – Carmine

回答

1

將對話框設置爲不可取消。

alertDialog.setCancelable(false); 

這樣它只能用命令dismiss()關閉;

你可以做到這一點與您的顯示對話框中設置,然後調用上面的命令是這樣的:

Dialog popup = alertDialog.show(); 

後來

popup.dismiss(); 

你也將需要時採取對話的護理屏幕旋轉,因爲它會消失。最好的選擇是在你的onSaveInstanceState裏保存一個布爾值,然後檢查onCreate裏面的狀態。

+0

謝謝,它做的工作 – Carmine

+0

@Carmine增加了一些額外的信息。如果幫助你,請選擇正確答案。 – Simas

+0

@Carmine有可能你的alertDialogue在點擊警報之外時仍然被忽略。 'alertDialog.setCanceledOnTouchOutside(假);'。用它來解決這個問題。 –

2

你這裏有兩種選擇:

要麼你可以設置警報不撤銷:

alertDialog.setCanceledOnTouchOutside(false); //This must be there. To avoid the alert getting dismissed on clicking outside the alert. 
alertDialog.setCancelable(false); //This is optional if you are going for the next option. I would say in your case YOU SHOULDN'T DO THIS. I will explain why. 

或者你可以覆蓋alertDialogue和finish()活動後退按鈕的動作。

alertDialog.setOnKeyListener(new Dialog.OnKeyListener() { 
    @Override 
    public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) { 
     if (keyCode == KeyEvent.KEYCODE_BACK) { 
      finish(); 
     } 
     return true; 
    } 
}); 

讓我略微說明爲什麼我做了第二個選項。根據您的問題,AlertDialogue中的按鈕啓動一個活動以提示用戶打開GPS。當我們寫這行時:

alertDialog.setCancelable(false); 

它實際上禁用後退按鈕。但是,那麼用戶將如何退出該應用?後退按鈕將被禁用,並且無法退出應用程序(警報上沒有任何按鈕可退出並且後退按鈕被禁用)。所以應該有一些方法讓用戶不必使用home按鈕就可以退出應用程序。我希望你明白我的觀點。

+0

@Downvoter,當你downvote時留下評論。這個問題有什麼問題? –

+0

爲什麼選擇這個? – Setu

+0

重寫onBackPressed的錯誤主意。此外,爲什麼重寫它,如果setCancelable阻止後退鍵功能? – Simas

相關問題