Control music player by using foreground service in android

0

I'm new to android development.I'm trying control music player with notification.till now,I have completed Songs list in a activity.when starts playing the foreground service is working fine and it is calling action by pending intent.my problem is when i click pause button service intent is called but,i could call main actitivy callPause() but it's showing null refrence for every datas.

Service Class

public class PlayerIntentService extends Service {

private static final String TAG = "ExampleJobIntentService";

private ModelSong currentSong;

private PendingIntent pendingIntent, playIntent, nextIntent, previousIntent,broadCastIntent;

private MediaSessionCompat mediaSession;

private boolean isPlay=true;

 @Override
public void onCreate() {
    super.onCreate();  
    mediaSession = new MediaSessionCompat(this, "Tag");

}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    currentSong = intent.getParcelableExtra("songData");

    if (intent.getAction() != null) {
        if (intent.getAction().equals("ACTION.PREV_ACTION"))
            Toast.makeText(this, "Clicked Previous", Toast.LENGTH_SHORT).show();
        else if (intent.getAction().equals("ACTION.PLAY_ACTION")) {
            isPlay =!isPlay;                
            new MainActivity().playPause(); 
            Toast.makeText(this, "From here i want to call mainActivity callPause()", Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(this, "Clicked Previous", Toast.LENGTH_SHORT).show();

    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        startMyOwnForeground();
    else
        showNotification();

    //do heavy work on a background thread
    //stopSelf();

    return START_STICKY;
}

private void showNotification() {
    startForeground(1, new Notification());
}


@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground() {

    initPendingIntents();

    String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
    String channelName = "My Background Service";
    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    Bitmap artwork = BitmapFactory.decodeResource(getResources(), R.drawable.vijay);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.search_icon)
            .setLargeIcon(artwork)
            .setContentIntent(pendingIntent)
            .setContentTitle("Song Tile")
            .setContentText("Artist name")
            .addAction(R.drawable.previous, "Previous", previousIntent)
            .addAction(isPlay ? R.drawable.ic_pause_black_24dp : R.drawable.ic_play_arrow, "play", playIntent)
            .addAction(R.drawable.next, "Next", nextIntent)
            .setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(1)
                    .setMediaSession(mediaSession.getSessionToken()))
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();


    startForeground(2, notification);

}

private void initPendingIntents() {

    Intent notificationIntent = new Intent(this, MainActivity.class);
    pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);


    Intent previous = new Intent(this, PlayerIntentService.class);
    previous.setAction("ACTION.PREV_ACTION");
    previousIntent = PendingIntent.getService(this, 1,
            previous, 0);

    Intent play = new Intent(this, PlayerIntentService.class);
    play.setAction("ACTION.PLAY_ACTION");
    playIntent = PendingIntent.getService(this, 2,
            play, 0);

    Intent next = new Intent(this, PlayerIntentService.class);
    next.setAction("ACTION.PREVIOUS_ACTION");
    nextIntent = PendingIntent.getService(this, 3,
            next, 0);

    Intent broadcastReceiver = new Intent(this, PlayerReceiver.class);
    broadcastReceiver.setAction("ACTION.BROADCAST_ACTION");
    broadCastIntent = PendingIntent.getBroadcast(this, 4,
            broadcastReceiver, 0);

}


@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    stopSelf();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

MainActivity.class

public void playPause() {
        if (mediaPlayer.isPlaying()) {
            imgPlayPause.setImageResource(R.drawable.play);
            playPauseN.setImageResource(R.drawable.ic_play_arrow);
            mediaPlayer.pause();
            adSongs.clearSelection();
        } else {
            imgPlayPause.setImageResource(R.drawable.pause);
            playPauseN.setImageResource(R.drawable.ic_pause_black_24dp);
            adSongs.updateSelection(currentSongIndex);
            mediaPlayer.start();
        }
    }

Error

  java.lang.RuntimeException: Unable to start service com.gowtham.musicplayerwithservice.adapters.PlayerIntentService@b738326 with Intent { act=ACTION.PLAY_ACTION flg=0x10000000 cmp=com.gowtham.musicplayerwithservice/.adapters.PlayerIntentService bnds=[186,750][330,894] }: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.media.MediaPlayer.isPlaying()' on a null object reference
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3687)
        at android.app.ActivityThread.access$1600(ActivityThread.java:200)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1682)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6692)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.media.MediaPlayer.isPlaying()' on a null object reference
        at com.gowtham.musicplayerwithservice.activities.MainActivity.playPause(MainActivity.java:482)
        at com.gowtham.musicplayerwithservice.adapters.PlayerIntentService.onStartCommand(PlayerIntentService.java:65)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3668)
        at android.app.ActivityThread.access$1600(ActivityThread.java:200) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1682) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6692) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
java
android
android-studio
asked on Stack Overflow Dec 6, 2019 by gowtham6672

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0