2017-08-13 111 views
0

每次用戶進入應用程序時,onResume()都在呼叫。如果用戶在警報對話框中沒有響應,則對話框只會累積。我想檢查是否已顯示對話框。警報對話多次呼叫

我發現這裏給予了極大的答案:Prevent dialog to be opened multiple times when resuming activity這裏How do I show only one Dialog at a time?但總是被一些錯誤而實施,在我的代碼

警報對話框

private AlertDialog.Builder showGPSDialog(Context con) { 

    AlertDialog.Builder builder = new AlertDialog.Builder(con); 
    builder.setTitle("Enable GPS"); 
    builder.setMessage("Please enable GPS"); 

    builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      startActivity(
        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
     } 
    }); 
    builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.dismiss(); 
     } 
    }); 
    return builder; 
} 

的onResume()

LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    boolean isEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

    if(!isEnabled) { 
     showGPSDialog(MapsActivity.this).show(); 
    } 

回答

1

你可以做的是把boolean isDialogBox顯示在sharedPreferences中,並將其設置爲true。當用戶點擊dialogBox的正面或負面按鈕。並檢查是否isDialogBox是的onResume

真正將這個代碼在OnCreate中

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
private AlertDialog.Builder showGPSDialog(Context con) { 

    AlertDialog.Builder builder = new AlertDialog.Builder(con); 
    builder.setTitle("Enable GPS"); 
    builder.setMessage("Please enable GPS"); 

    builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
     prefs.edit().putBoolean("isShown", true).commit(); 
      startActivity(
        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
     } 
    }); 
    builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
     prefs.edit().putBoolean("isShown", true).commit() 
      dialog.dismiss(); 
     } 
    }); 
    return builder; 
} 

這的onResume

LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
boolean isEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

if(!(prefs.getBoolean("isShown", false))) { 
    showGPSDialog(MapsActivity.this).show(); 
} 
1

剛關閉onPause方法的對話框,你將只能有一個顯示

@Override 
protected void onPause(){ 
super.onPause(); 

}