Android: Ошибка уведомления на музыкальном проигрывателе.

Я разрабатываю музыкальный плеер с сервисом. В настоящее время с упором на уведомления и кнопки...

Теперь у меня есть кнопки на панели уведомлений Play, Next, Previous.. Я хочу отобразить кнопку паузы, если мультимедиа воспроизводится, и кнопку Play, если не воспроизводится...

Ошибка в том, что, когда я добавил условие If в уведомлении.addction, он показывает красные линии..

Я сделал код, который показывает ошибку...

Сервисный код...

Foreground.java (Имя класса)..

public class ForegroundService extends Service {
    private static final String LOG_TAG = "ForegroundService";
    public static boolean IS_SERVICE_RUNNING = false;
    final MediaPlayer mp=new MediaPlayer();

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Start Foreground Intent ");
            showNotification();
            //-------------------------------------------

            try{
                //you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
                mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/downloadedfile.mp3");

                mp.prepare();
            }catch(Exception e){e.printStackTrace();}


            mp.start();


            //-------------------------------------
            Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();

        } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
            Log.i(LOG_TAG, "Clicked Previous");

            Toast.makeText(this, "Clicked Previous!", Toast.LENGTH_SHORT)
                    .show();
        } else if (intent.getAction().equals(Constants.ACTION.PAUSE_ACTION)) {
            Log.i(LOG_TAG, "Clicked Play");


            Toast.makeText(this, "Clicked Play!", Toast.LENGTH_SHORT).show();
        } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
            Log.i(LOG_TAG, "Clicked Next");

            Toast.makeText(this, "Clicked Next!", Toast.LENGTH_SHORT).show();
        } else if (intent.getAction().equals(
                Constants.ACTION.STOPFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Stop Foreground Intent");
            stopForeground(true);
            stopSelf();
        }
        return START_STICKY;
    }

    private void showNotification() {

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        Intent previousIntent = new Intent(this, ForegroundService.class);
        previousIntent.setAction(Constants.ACTION.PREV_ACTION);
        PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                previousIntent, 0);

        Intent playIntent = new Intent(this, ForegroundService.class);
        playIntent.setAction(Constants.ACTION.PLAY_ACTION);
        PendingIntent pplayIntent = PendingIntent.getService(this, 0,
                playIntent, 0);


//---------------------------------------------------------------------------------
        Intent pauseIntent = new Intent(this, ForegroundService.class);
        pauseIntent.setAction(Constants.ACTION.PAUSE_ACTION);
        PendingIntent ppauseIntent = PendingIntent.getService(this, 0,
                playIntent, 0);
//------------------------------------------------------------------------


        Intent nextIntent = new Intent(this, ForegroundService.class);
        nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
        PendingIntent pnextIntent = PendingIntent.getService(this, 0,
                nextIntent, 0);

        Bitmap icon = BitmapFactory.decodeResource(getResources(),
                R.drawable.aa);

        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("TutorialsFace Music Player")
                .setTicker("TutorialsFace Music Player")
                .setContentText("My song")
                .setSmallIcon(R.drawable.aa)
                .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .addAction(android.R.drawable.ic_media_previous, "Previous",
                        ppreviousIntent)
//---------------------------------------------------------------------------
                if(mp.isPlaying()){
                    .addAction(android.R.drawable.ic_media_play, "Play",
                            pplayIntent)
                }
        else{
                    .addAction(android.R.drawable.ic_media_pause, "Pause",
                            pplayIntent)
                }

//------------------------------------------------------------------------------------------------

                .addAction(android.R.drawable.ic_media_next, "Next",
                        pnextIntent).build();
        startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
                notification);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG_TAG, "In onDestroy");
        Toast.makeText(this, "Service Detroyed!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Used only in case if services are bound (Bound Services).
        return null;
    }
}

Код, который я добавил, помещен в линию.....

Может кто-нибудь предложить мне точный код или Displayig кнопку воспроизведения и паузы одновременно?? Спасибо

2 ответа

Поставьте точку с запятой перед if, а затем используйте объект уведомления, чтобы установить действие следующим образом:

if (mp.isPlaying ())tification.addAction(android.R.drawable.ic_media_play, "Play", pplayIntent); еще уведомление.addAction(android.R.drawable.ic_media_pause, "Пауза", pplayIntent);

Я полагаю, это сделает вашу работу

Я предлагаю вам использовать пользовательский вид для медиаплеера. Вот здесь учебник, как вы можете это сделать. Короче говоря: вам нужно использовать:

notification = new Notification.Builder(this).build();
notification.contentView = views;
notification.bigContentView = bigViews;

предоставлять настраиваемые и расширенные настраиваемые представления.

Далее вам необходимо обновить уведомление не только тогда, когда вы начинаете его показывать, но и в любое время, когда вы нажимаете кнопки воспроизведения или паузы. Так что вам нужно изменить:

} else if (intent.getAction().equals(Constants.ACTION.PAUSE_ACTION)) {
    Log.i(LOG_TAG, "Clicked Play");
    Toast.makeText(this, "Clicked Play!", Toast.LENGTH_SHORT).show();
} 

На

} else if (intent.getAction().equals(Constants.ACTION.PAUSE_ACTION)) {
    Log.i(LOG_TAG, "Clicked Pause");
    mp.pause();
    showNotification();
    Toast.makeText(this, "Clicked Pause!", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
    Log.i(LOG_TAG, "Clicked Play");
    mp.start();
    showNotification();
    Toast.makeText(this, "Clicked Play!", Toast.LENGTH_SHORT).show();
} 

Что-то вроде того. Надеюсь, у вас есть основная идея.

Другие вопросы по тегам