2016-04-17 11 views
0

[OK]を起動している理由のAndroid Broadcastreceiver、そこに記載されているID documentationは:
ポップアップが

あなたは の実装onReceive()でポップアップダイアログを起動することはできません。

それにもかかわらず、このコードはbeatufilly働いている:なぜそれが働いている

public class MainActivity extends AppCompatActivity { 
    final String ACTION = "myActionForBroadcast"; 

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Log.d("MyTag", "onReceive: context" + context.getPackageCodePath()); 
      showDialog(); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     IntentFilter filter = new IntentFilter(); 
     filter.addAction(ACTION); 
     registerReceiver(broadcastReceiver, filter); 

     final Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       Log.d("MyTag", "Handler run: before send broadcast"); 
       sendBroadcast(new Intent(ACTION)); 
      } 
     }, 5_000); 
    } 

    private void showDialog() { 
     final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 

     builder.setTitle("Title"); 
     builder.setMessage("Message"); 

     builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       Toast.makeText(MainActivity.this, "Dialog: onClick()", Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     Log.d("MyTag", "showDialog: before showing dialog"); 
     builder.show(); 
     Log.d("MyTag", "showDialog: before showing toast"); 
     Toast.makeText(MainActivity.this, "showDialog: showing toast", Toast.LENGTH_SHORT).show(); 
    } 
} 

?私はドキュメンテーションで何が欠けていますか? ありがとうございました。

+1

ええ、それはあまりうまく書かれていません。彼らが言っていることは、 'onReceive()'に渡された 'Context'を使って' Dialog'を作成して表示できないということです。 'Dialog'は' Activity''Context'を必要とします。 'Context'は' onReceive() 'に渡されます。あなたのケースでは、 'BroadcastReceiver'は' MainActivity'の内部クラスであり、 'MainActivity'の' Context'を使って 'Dialog'を作成しています。 –

+0

ああ、大丈夫です。私は来るコンテキストがBroadcastRestrictedContextなのを見ました。しかしトーストはこの文脈で見ることができますよね? –

+1

はい、その 'Context'で' Toast'を表示することができます。 –

答えて

1

私の意見では、あなたの 'showDialog()'メソッドは、許容されていないBroadcastReceiverからのコンテキストを使用するのではなく、許可されたアクティビティ(あなたのMainActivity)からコンテキストを使用して呼び出されます。 詳細については、この回答を参照することができます。show an alert dialog in broadcast receiver after a system reboot

関連する問題