I am working on a custom notification where I am using RemoteViews for customizing the notification layout. Everything works fine except the problem I am facing when the Service class gets crashes and called again by itself, my global value created for the RemoteView becomes null. So eventually it is throwing NullPointerException
.
Service class crash scenario:
While starting an activity from the notification through PendingIntent
and when the user swipes the activity from the recent task, my app is getting crashed. For this purpose I have applied some sort of logics as follows:
(i) Changed the return type of onStartCommand
method in a Service class from START_STICKY
to START_STICKY_COMPATIBILITY
(Using this because previous intent called after when service restarts)
(ii) Checked null
condition of intent as follows:
//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:
I have a music player with play and pause and I need to handle the play/pause case based on the PendintIntent
assigned for the view.
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: Whenever the onStartCommand()
is called, based on the notification type I am updating the type of notification. The type is based on the Intent
flags which is assigned while starting the Service
.
I have been stuck up with this issue for more than a week. Please help me to rectify the issues. Any sort of tips or suggestions would be helpful for me. Thanks in advance.