我正在处理自定义通知,我使用RemoteViews来自定义通知布局 . 一切正常,除了我遇到的问题,当Service类崩溃并再次自己调用时,我为RemoteView创建的全局值变为null . 所以最终它会抛出 NullPointerException
.
Service class crash scenario:
通过 PendingIntent
从通知启动活动时,当用户从最近的任务中滑动活动时,我的应用程序正在崩溃 . 为此我已经应用了某种逻辑,如下所示:
(i) 将Service类中 onStartCommand
方法的返回类型从 START_STICKY
更改为 START_STICKY_COMPATIBILITY
(使用此方法,因为以前在服务重新启动时调用的意图)
(ii) 检查 null
意图条件如下:
//If the intent is null, do not execute the switch statement. If it is not null perform the action.
if (intent==null)
return 0;
My Requirement:
我有一个播放和暂停的音乐播放器,我需要根据为视图分配的 PendintIntent
处理播放/暂停情况 .
Code using for the PendingIntent on clicking the view:
Intent intent = new Intent(context, ServiceExample.class);
intent.setAction(CLICK_PLAY_PAUSE);
PendingIntent musicPlayPauseClickIntent = PendingIntent.getService(context, 0,intent, 0);
mRemoteViewsMusics.setOnClickPendingIntent(R.id.img_play_pause, musicPlayPauseClickIntent);
Code using for opening an activity on click of the thumbnail in the notifications:
Intent openAcivityIntent = new Intent(context, toClass);
openAcivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent.getActivity(context,0,openAcivityIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Code using for Handling the click events in the Service class.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
case CLICK_PLAY_PAUSE:
//NOTE: Getting `NullPointerException` on mRemoteViewsMusics
mRemoteViewsMusics.setImageViewResource(R.id.img_play_pause,
R.drawable.ic_noti_pause_circle);
mMediaPlayer.start();
break;
return START_STICKY_COMPATIBILITY;
case TYPE_MUSIC:
showMusicNotification();
break;
}
Code for creating a RemoteViews:
public void showMusicNotification(){
private RemoteViews mRemoteViewsMusics;
mRemoteViewsMusics = new RemoteViews(getPackageName(),
R.layout.music_notification);
}
Note: 每当调用 onStartCommand()
时,根据通知类型我正在更新通知类型 . 该类型基于 Intent
标志,该标志在启动 Service
时分配 .
一个多星期以来,我一直坚持这个问题 . 请帮我纠正这个问题 . 任何形式的建议或建议对我都有帮助 . 提前致谢 .