【问题标题】:Android get extra in receiver after reboot重启后Android在接收器中获得额外的
【发布时间】:2015-08-12 13:59:16
【问题描述】:

我正在开发一个提醒用户的应用程序。它运行良好,但是当我设置它并重新启动设备时,通知返回 null。我认为问题出在广播接收器上。因为无法从额外的意图中获得任何字符串。

-- 在活动中--

private void setAlarm() {
    Intent myIntent = new Intent(this, AlarmReceiver.class);
    String data = descripton.getText().toString();
    Bundle b = new Bundle();
    b.putString("notify_message", data);
    myIntent.putExtras(b);
    pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
}

-- 清单--

 <receiver  android:name=".ekstra.AlarmReceiver"
            android:enabled="true"
            android:exported="true"
            android:label="StartMyServiceAtBootReceiver">
            <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

-- 广播接收器--

@Override
public void onReceive(Context context, Intent intent) {
    try {
        Bundle extras = intent.getExtras();
        //Afret reboot test1 and test2 is null
        String test1 = extras.getString("notify_message");
        String test2 = intent.getStringExtra("notify_message");
        Intent newIntent = new Intent(context, RemindingService.class);
        newIntent.putExtra("messaage", message);
        context.startService(newIntent);
    } catch (Exception e) {
        Log.e("Test", "error " + e.toString());
    }
}

【问题讨论】:

  • 重新启动后,您将不再接收这些广播,因为您的 AlarmManager 计划将被清除。
  • 不,我可以接收广播并获得通知,但重启后它总是空值,这是我的问题
  • 然后你在某处重新安排你的闹钟,而在某处你忘记设置你的附加功能。我再说一遍:您的AlarmManager 计划将在重新启动时消失。
  • 非常感谢这是我的错 :) 你是对的

标签: android broadcastreceiver alarm reboot


【解决方案1】:

如上所述,重启后您将不会收到广播。 但是在这里,如果您在启动完成时调用相同的 AlarmReceiver,这是由 System 广播的,那么下面将返回 null

String test1 = extras.getString("notify_message");//test1 is null

String test2 = intent.getStringExtra("notify_message");//test2 is null

(两个调用是等价的)

因此,您应该根据是在启动后调用 Receiver 还是由于警报来执行您的逻辑。您可以在 AlarmReceiver 中执行以下操作:

String msg = intent.getStringExtra("notify_message");
if(msg==null){
      //means that receiver started after boot
      // write your logic here
}else{
      //means that receiver started by alarm
      //write your logic here
}

【讨论】:

  • 那么有没有办法存储一个特定的值以在重启后检索?如果您需要传递用户定义的值以在重新启动后(不使用 sharedpreferences),您将如何恢复该值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 2021-07-09
  • 2017-05-22
  • 2012-01-15
相关资源
最近更新 更多