2014-01-17 73 views
0

我試圖讓對話框觸發一個意圖,然後關閉。使用意圖啓動服務後關閉對話框

public class PinMessage extends DialogFragment { 


public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the Builder class for convenient dialog construction 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    Random random = new Random(); 
    final int pin = random.nextInt(9000) +1000; 
    builder.setMessage("Your pin is " + (pin)+". Please note in case of password loss.") 
    .setTitle("Security PIN") 
      .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        SharedPreferences launch_track = PreferenceManager 
         .getDefaultSharedPreferences(MainActivity.context); 
       SharedPreferences.Editor editor1 = launch_track.edit(); 
       editor1.putInt("pin", pin); 
       editor1.commit(); 


          //This triggers before the dialog closes 
       Intent lock = new Intent(context,AppLockService.class); 
         context.startService(lock); 


        // FIRE ZE MISSILES! 
       } 

      }); 


    // Create the AlertDialog object and return it 
    return builder.create(); 
} 

} 

單擊確定按鈕,除了觸發意圖和啓動服務之外,我還希望關閉對話框。

當前,當我按OK時,意圖被觸發並且服務在後臺啓動,但對話框沒有關閉,我必須按下電話按鈕才能退出。請幫幫我。

回答

3
public void onClick(DialogInterface dialog, int id) 

添加dialog.dismiss();正如你可以看到你有存取要求方法中的對話框,只需調用解僱:

dialog.dismiss(); 
+0

哈哈。它非常簡單。感謝您的解決方案。 :) – SoulRayder

+0

+1與您的答案:) –

+0

接受答案,如果它爲你工作:) –

1

創建AlertDialog的參考

AlertDialog alertDialog = builder.create(); 
builder.setPositiveButton("OK", new OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 
      // Start the Service and your required code 
      alertDialog.dismiss(); 
     } 
    }); 
return alertDialog; 

OR

您將得到對話框參考直通的的onClick

@Override 
    public void onClick(DialogInterface dialog, int which) { 
     // TODO Auto-generated method stub 
     // Start the Service and your required code 
     dialog.dismiss(); 
    } 
+0

創建此引用不必要的,因爲你已經在方法中有一個參考,(DialogInterface對話框,int) –

+0

雅你說得對,同意你的一個swer :) –

0

您可以使用此做

dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { 

    @Override 
    public void onDismiss(DialogInterface dialog) { 
     //your implementation while on dismiss 
    } 
}); 

而且在onClick