Android,service向broadCastReceiver传递数据为null
在service中设置了一个闹钟,会通过intent传递一些数据启动BroadCastReceiver,receiver中取到数据,在通知栏显示notification
Service代码
public class RemindService extends Service {
List<Remind> reminds;
public RemindService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String remindsStr = intent.getStringExtra("reminds");
reminds = JSON.parseArray(remindsStr, Remind.class);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
for (Remind remind : reminds) {
Intent intent1 = new Intent(getApplicationContext(), RemindReceiver.class);
intent.putExtra("content", remind.getTitle());
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent1, 0);
if (remind.getFrequencyType() == Remind.TYPE_ONCE) {
manager.setExact(AlarmManager.RTC_WAKEUP, getAlarmTimeByRemind(remind), pi);
} else {
...
}
}
return super.onStartCommand(intent, flags, startId);
}
BroadCastReceiver代码:
public class RemindReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
LogUtil.d("content:" + intent.getStringExtra("content")); //此处获取的context为null
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title")
.setContentText(intent.getStringExtra("content"))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.build();
manager.notify(1, notification);
这是AndroidManifest.xml
<application
android:name=".util.TApplication"
android:allowBackup="true"
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
... //一些activity
<service
android:name=".service.RemindService"
android:enabled="true"
android:exported="false" />
<receiver
android:name=".receiver.RemindReceiver"
android:enabled="true"
android:exported="false"/>
</application>
调试了半天不知道为什么。在Service的for循环中是remind.getTitle()有值的,调试时看到了。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)