2012-10-26 68 views
3

我想在設備引導完成時顯示警報對話框。廣播接收機沒有問題,它工作正常。但是啓動完成後,沒有任何公開活動,因此我在此處獲得NullPointerException。如何在這種情況下顯示對話框?這是我用來顯示對話框的代碼:BOOT_COMPLETED後的警報對話框中的空指針異常

public class RestartReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 

     AlertDialog alertHelp; 
     AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
     TextView m_timetext = new TextView(context); 
     m_timetext.setText("hello"); 
     // m_timetext.setTextColor(getResources().getColor(R.color.dark_green)); 

     LinearLayout linearLayout = new LinearLayout(context); 
     linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 
       LinearLayout.LayoutParams.FILL_PARENT)); 
     linearLayout.setOrientation(1); 
     linearLayout.addView(m_timetext); 

     dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 

      }}); 

     dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 

      }}); 

     alertHelp = dialog.create(); 
     alertHelp.setView(linearLayout); 
     alertHelp.show();  

     Log.d("In","Switched On"); 
    } 
} 

請幫助我。提前致謝。

+0

請幫幫我。 – user1726619

+2

哪一行給你空指針? – Carnal

+0

alertHelp.show() - >這裏我得到異常先生。 – user1726619

回答

3

以下是關於如何操作的post。您可以從here獲取源代碼。

您的代碼不起作用,因爲您無法直接從您的廣播接收器顯示對話框。您必須使用Activity。此外,爲了接收ACTION_BOOT_COMPLETED您的活動必須首先由用戶或其他應用程序明確啓動(谷歌應用程序停止狀態以獲取更多信息)。

基本上實現所需的功能,你需要做的:

  1. 創建透明的活動,顯示對話框。
  2. 創建BroadcastReceiver接收ACTION_BOOT_COMPLETED並開始您的活動。
  3. 在清單中註冊您的廣播接收器並獲得適當的許可。

另外,this問題提供了有關如何創建透明活動的更多信息。