我正在将一个Int传递给BroadcastReceiver,但我不确定我是否正确操作,因为有时候它有效,有时却没有。
发送Int:
Intent intent = new Intent(getActivity(),Broadcast_RemoveClass.class);
Bundle bundle = new Bundle();
bundle.putDouble("mInt", i);
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 5, pendingIntent);
Toast.makeText(getActivity(), "countdown started for: " + i,Toast.LENGTH_LONG).show();
获取Int:
public class Broadcast_RemoveClass extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int i = bundle.getInt("mInt");
Toast.makeText(context, "done" + i , Toast.LENGTH_LONG).show();
}
}
有时它会得到当前的int但是它只是得到了一个点,它只是继续获得前一个传递的int。发送intent时,它会在toast中显示正确的int,但是在BroadcastReceiver中它会得到一个错误的int。是什么让这种情况发生的想法?
答案 0 :(得分:0)
我解决了它而不是通过数据包传递数据,我只是将数据放在SharedPrefs键中,然后在BroadcastReceiver中获取该键
发送强>
prefs = getActivity().getSharedPreferences("info", Context.MODE_PRIVATE);
prefs.edit().putInt("mInt", i).apply();
得到它:
SharedPreferences prefs = context.getSharedPreferences("info", Context.MODE_PRIVATE);
int i = prefs.getInt("i",0);
我希望这有助于任何人