1

I am running audio player service but If I put my phone on sleep the player stops or the background service I don't know what's the problem.

this is my music service class :

public class MusicService extends Service {

    public static final String ACTION_NEXT = "NEXT";
    public static final String ACTION_PREV = "PREVIOUS";
    public static final String ACTION_PLAY = "PLAY";
    public static final String ACTION_FORWARD = "FORWARD";
    public static final String ACTION_REWIND = "REWIND";
    public static final String ACTION_CONTINUE = "CONTINUE";
    ActionPlaying actionPlaying;
    Action action;

    private final IBinder mBinder = new MyBinder();



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



    public class MyBinder extends Binder {
        MusicService getService() {
            return MusicService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


    String actionName = intent.getStringExtra("myActionName");

        if (actionName != null) {
            switch (actionName)
            {
                case ACTION_PLAY:
                    if(actionPlaying!= null){
                        if(action!= null){
                        actionPlaying.playClicked();
                        action.playPauseClicked();
                    }}
                    break;
                case ACTION_NEXT:
                    if(actionPlaying != null){
                        actionPlaying.nextClicked();
                    }

                    break;
                case ACTION_PREV:
                    if(actionPlaying != null){
                        actionPlaying.prevClicked();

                    }

                    break;
                case ACTION_FORWARD:
                    if(actionPlaying != null){
                        actionPlaying.forwardClicked();
                    }
                    break;
                case ACTION_REWIND:
                    if(actionPlaying != null){
                        actionPlaying.rewindClicked();
                    }
                    break;
                case ACTION_CONTINUE:
                    Toast.makeText(this, "continue", Toast.LENGTH_SHORT).show();
                        action.continueMediaPlayer();

            }
        }
        return START_STICKY;
    }


    public void setCallBack(ActionPlaying actionPlaying){
        this.actionPlaying =  actionPlaying;
    }


    public void setCallBack(Action action) {
        this.action =  action;
    }

    public void onTaskRemoved(Intent rootIntent) {
            super.onTaskRemoved(rootIntent);
           notificationManager.cancelAll();
         saveData();
        simpleExoPlayer.release();

    }

}

and this is my media player initialization :

public void prepareMedia() {
        isPlaying=true;
        simpleExoPlayer = new SimpleExoPlayer.Builder(MediaPlayer_Activity.this).build();
        MediaItem mediaItem = MediaItem.fromUri(audioUrl);
        simpleExoPlayer.addMediaItem(mediaItem);
        simpleExoPlayer.prepare();
        simpleExoPlayer.seekTo(songPrevPosition);
    }

Please tell me what's wrong LogCat is not showing anything I don't know how to stop this and where the problem is.... please help

Omar Shawky
  • 1,242
  • 1
  • 12
  • 25

3 Answers3

0

After 9 Android version we have protections for simple service. Simple service can live 10 seconds, no more. You need to declare you service as Foreground Service. It will look like notification in status bar.

For fully information read documentation

0

according to Android Developers documentation :

  • You need to upgrade your background process to foreground inorder to make it live without needing your application to be visible to the user.
  • in order to change your service to foreground one, your service need to have a notification to inform the user that your music player service is working.

a simple foreground service code might look like this :

 public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Notification notification = buildStartingNotification();
        startForeground(startId, notification);
        ...
        return START_STICKY;
    }
private Notification buildStartingNotification() {

    int priority  =NotificationCompat.PRIORITY_LOW;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        priority = NotificationManager.IMPORTANCE_LOW;
        createNotificationChannel(priority);
    }
    Notification notification =
              new Notification.Builder(this,CHANNEL_ID)
        .setContentTitle("Your_notification_title")
        .setContentText("Your_notification_description ")
        .setSmallIcon(R.drawable.icon)
        .setPriority(priority)
        .build();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel(int priority) {
        CharSequence name = getText("Your_Channel_Name");
        String description = getString("Your_Channel_Desc");
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, priority);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
}

N.B : if you're using application with (target_api > 26) you need to have also a notification channel which I included its code in createNotificationChannel, where your CHANNEL_ID could be any unique string id you want.
if you're wandering what's the meaning of notification channel ?
a notification channel is a mechanism built for android 8 or later to make the user turn off/on group of notification with same channel at once from setting.
as an example your application might have multiple notification channels (news/games/entertainment...etc), then the user can turn off news &games and leave only entertainment on.

Omar Shawky
  • 1,242
  • 1
  • 12
  • 25
-1

First of all make sure you use foreground service. I suggest to you to start permanent notification like this:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            NotificationChannel channel;
 Intent notifyIntent = new Intent(this, SomeActivity.class);
            notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification notification = showStableMessage(this,
                    getString(R.string.app_desc),
                    "Message to user",
                    R.mipmap.ic_icon,
                    notifyPendingIntent);

            startForeground(NotificationUtil.STABLE_CHANNEL_NOTIFY_ID, notification);
        return  Service.START_STICKY;
    }

    private Notification showStableMessage(Context context, String title, String message, int icon, PendingIntent intent) {
        NotificationChannel channel;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel = new NotificationChannel(STABLE_CHANNEL_ID,
                    STABLE_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);
            ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
        }

        Notification notification =  new NotificationCompat.Builder(context, STABLE_CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(Html.fromHtml(message)).setPriority(PRIORITY_DEFAULT)
                .setSmallIcon(icon)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setContentIntent(intent)
                .setCategory(NotificationCompat.CATEGORY_SERVICE).build();
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        return notification;
    }

Second you have to put this in manifest:

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
.....>
    <service
                android:name=".data.service.MyService"
                android:foregroundServiceType="mediaPlayback"
                android:enabled="true"/>
</application>
Alex Rmcf
  • 804
  • 7
  • 14