0

私は、SecondActivityを起動する起床サービス(IntentService)を起動するWakefulBroadcastReceiver(MainActivityでアラームが設定されている)を使用してアラームアプリケーションを作成しようとしています。しかし、私はMainActivityからSecondActivityへのデータをインテントを使って渡す方法を理解することはできませんでした。これは、アラームを設定するためのコードです:サービスによって開始されたアクティビティへのデータの受け渡し

Intent intent = new Intent(MainActivity.this, AlarmReceiver.class); 
intent.putExtra("requestCode", 111); 
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 111, intent, 0); 
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), pendingIntent); 

AlarmReceiverでonReceiveのためのコード:

Intent service = new Intent(context, AlarmService.class); 
intent.putExtra("requestCode", intent.getIntExtra("requestCode", 222)); 
startWakefulService(context, service); 

アラームサービスでonHandleIntentのためのコード:最後に

Context context = getApplicationContext(); 
Intent intent = new Intent(context, SecondActivity.class); 
intent.putExtra("requestCode", intent.getIntExtra("requestCode", 333)); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
context.startActivity(intent); 

、SecondActivityのonCreateで私は次のコードを持っています:

Intent intent = getIntent(); 
Log.i("APP", "requestCode: " + intent.getIntExtra("requestCode", 444)); 

出力はAlarmServiceのonHandleIntentのデフォルト/フェイルセーフ値(111の元の要求コードではありません)であったrequestCode: 333です。私は何が欠けていますか?

編集:onReceiveのコードは次のようになります。

Intent service = new Intent(context, AlarmService.class); 
service.putExtra("requestCode", intent.getIntExtra("requestCode", 222)); 
startWakefulService(context, service); 

そして、それは問題を修正します。あなたがしている1 - あなたは古いものを参照していないしている二行目が、新しいにおけるので、あなたのサービスで受信した1つとしてあなたの新しい意図同じ名前のき

答えて

0
Intent intent = new Intent(context, SecondActivity.class); 
intent.putExtra("requestCode", intent.getIntExtra("requestCode", 333)); 

初期化しようとしています - これは余分なものがありませんので、デフォルト値に解決されます。変更:

Intent activityIntent = new Intent(context, SecondActivity.class); // or any other name different than 'intent' 
activityIntent.putExtra("requestCode", intent.getIntExtra("requestCode", 333)); 

それ以外は、あなたのコードは大丈夫です。

+0

実際に、私は本当にダムの間違いをしたことに気付きました。私は 'service.putExtra'の代わりに' onReceive'に 'intent.putExtra'を書いて、それを解決しました。あなたが指摘したセクションを変更して、確かめてください! – Technicolor

関連する問題