使用RemoteViews的通知不起作用

时间:2015-06-14 10:57:08

标签: android notifications android-mediaplayer android-remoteview

我正在尝试发出自定义通知(具有播放暂停,下一个和上一个按钮)。但这似乎不起作用:

  • 我想要的内容:从我的活动中发出带有播放暂停,下一个和上一个按钮的自定义通知。此活动有一个有效的MediaPlayer

  • 有什么问题:根本不会发出通知。

  • 我做了什么:MediaPlayer完成后,从我的Activity onCreate()调用以下代码:

非常感谢任何帮助。谢谢!!

    private void sendNotification() {

        Log.v(LOGTAG, "Inside sendNotification");

        // Creating RemoteView and inflating it with a custom XML layout file    
        RemoteViews notificationViews = new RemoteViews(getPackageName(), R.layout.notification);

        Updating some fields in the layout file
        notificationViews.setTextViewText(R.id.songNameTextViewNotify, trackInfo.getTrack());
        notificationViews.setImageViewUri(R.id.songImageViewNotify, Uri.parse(trackInfo.getAlbumImageURL()));

        // Notification builder    
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).
                setContent(notificationViews);

                // Pending intent to call my class
                // The intent will be caught in the onNewIntent() method
        Intent intent = new Intent(this, MusicPlayer.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notificationViews.setOnClickPendingIntent(R.id.playPauseButtomNotify, pendingIntent);

        // Issuing new Notification    
        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        Log.v(LOGTAG, "Sending Notification");
        notificationManager.notify(NOTIFICATION_ID, builder.build());

    }

Notification.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/songImageViewNotify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/no_image"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/songNameTextViewNotify"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:gravity="center"/>


        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/previousButtomNotify"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@android:drawable/ic_media_previous"
                android:onClick="playPreviousTrackNotify"/>

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <ImageButton
                android:id="@+id/playPauseButtomNotify"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@android:drawable/ic_media_pause"
                android:onClick="playOrPauseNotify"/>

            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <ImageButton
                android:id="@+id/nextButtomNotify"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@android:drawable/ic_media_next"
                android:onClick="playNextTrackNotify"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

MusicPlayer.java的完整内容

 package com.example.deep.musico;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;


public class MusicPlayer extends ActionBarActivity implements MediaPlayer.OnPreparedListener {

    private int playTrack;
    private ArrayList<TrackInfo> trackList ;

    public static final String PLAY_URL = "url";
    private static final String LOGTAG = "MusicPlayer";
    private static int elapsedTime ;
    private static int remainingTime;

    TextView artistName;
    TextView albumName;
    ImageView albumImage;
    TextView songName;
    SeekBar songProgress;
    TextView startTime;
    TextView endTime;
    ImageButton previousSong;
    ImageButton playPause;
    ImageButton nextSong;
    TrackInfo trackInfo;

    MediaPlayer mediaPlayer;
    WifiManager.WifiLock wifiLock;
    Handler seekBarHandler = new Handler();
    private int NOTIFICATION_ID = 1;

    private Runnable seekBarUpdate = new Runnable() {
        @Override
        public void run() {
            if(mediaPlayer != null) {

                elapsedTime = (int) mediaPlayer.getCurrentPosition();
                remainingTime = (int) mediaPlayer.getDuration() - elapsedTime;

//                Log.v(LOGTAG, "Elapsed time from runnable : " + mediaPlayer.getCurrentPosition());
//                Log.v(LOGTAG, "Remaining time from runnable : " + remainingTime);

                String formatTimeStart = String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(elapsedTime),
                        TimeUnit.MILLISECONDS.toSeconds(elapsedTime) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(elapsedTime)));

                String formatTimeEnd = String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(remainingTime),
                        TimeUnit.MILLISECONDS.toSeconds(remainingTime) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remainingTime)));

                Log.v(LOGTAG, "Formatted start time : " + formatTimeStart);
                Log.v(LOGTAG, "Formatted end time : " + formatTimeEnd);

                startTime.setText(formatTimeStart);
                endTime.setText(formatTimeEnd);

                songProgress.setProgress(elapsedTime);
                seekBarHandler.postDelayed(seekBarUpdate, 50);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        playTrack = getIntent().getIntExtra(SongsActivityFragment.PLAY_TRACK, 0);
        trackList = getIntent().getParcelableArrayListExtra(SongsActivityFragment.ALL_TRACKS);

        init();
        init(playTrack);

        sendNotification();

//        Intent intent = new Intent(this, PlayMusicService.class);
//        intent.putExtra(PLAY_URL, trackList.get(playTrack).getPreviewURL());
//        startService(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.v(LOGTAG, "In new Pending Intent ");
    }

    private void sendNotification() {

        Log.v(LOGTAG, "Inside sendNotification");

        RemoteViews notificationViews = new RemoteViews(getPackageName(), R.layout.notification);

        notificationViews.setTextViewText(R.id.songNameTextViewNotify, trackInfo.getTrack());
        notificationViews.setImageViewUri(R.id.songImageViewNotify, Uri.parse(trackInfo.getAlbumImageURL()));

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).
                setContent(notificationViews);

        Intent intent = new Intent(this, MusicPlayer.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notificationViews.setOnClickPendingIntent(R.id.playPauseButtomNotify, pendingIntent);

        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        Log.v(LOGTAG, "Sending Notification");
        notificationManager.notify(NOTIFICATION_ID, builder.build());

    }

    private void init() {

        artistName = (TextView) findViewById(R.id.artistNameTextView);
        albumName = (TextView) findViewById(R.id.albumNameTextView);
        albumImage = (ImageView) findViewById(R.id.albumImageView);
        songName = (TextView) findViewById(R.id.songNameTextView);
        songProgress = (SeekBar) findViewById(R.id.songProgressBar);
        startTime = (TextView) findViewById(R.id.startTimeTextView);
        endTime = (TextView) findViewById(R.id.endTimeTextView);
        previousSong = (ImageButton) findViewById(R.id.previousButtom);
        playPause = (ImageButton) findViewById(R.id.playPauseButtom);
        nextSong = (ImageButton) findViewById(R.id.nextButtom);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
        mediaPlayer.setOnPreparedListener(this);

        wifiLock = ((WifiManager) getSystemService(WIFI_SERVICE)).
                createWifiLock(WifiManager.WIFI_MODE_FULL, "MusicLock");
        wifiLock.acquire();
    }

    private void init(int trackNumber){

        if(mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
        }

        trackInfo = trackList.get(trackNumber);

        artistName.setText(trackInfo.getArtist());
        albumName.setText(trackInfo.getAlbum());

        if(! (trackInfo.getAlbumImageURL().equals(""))) {
            Picasso.with(this).load(trackInfo.getAlbumImageURL()).into(albumImage);
        }

        elapsedTime = 0;
        startTime.setText(String.valueOf(elapsedTime));

        remainingTime = (int) mediaPlayer.getDuration();
        endTime.setText(String.valueOf(remainingTime));

        songName.setText(trackInfo.getTrack());
        songProgress.setProgress(elapsedTime);

//        Moving below line to Runnable because mediaPlayer.getDuration() does not return right value
        songProgress.setMax(30 * 1000);

        Log.v(LOGTAG, "Duration from track info : " + String.valueOf(trackInfo.getDuration()));
        Log.v(LOGTAG, "Duration from mediaPlayer : " +String.valueOf(mediaPlayer.getDuration()));

        Log.v(LOGTAG, trackInfo.getPreviewURL());
        try {
            mediaPlayer.setDataSource(trackInfo.getPreviewURL());
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.prepareAsync();

        songProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }

                elapsedTime = (int) mediaPlayer.getCurrentPosition();
                remainingTime = (int) mediaPlayer.getDuration() - elapsedTime;

//                Log.v(LOGTAG, "Elapsed time from runnable : " + mediaPlayer.getCurrentPosition());
//                Log.v(LOGTAG, "Remaining time from runnable : " + remainingTime);

                String formatTimeStart = String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(elapsedTime),
                        TimeUnit.MILLISECONDS.toSeconds(elapsedTime) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(elapsedTime)));

                String formatTimeEnd = String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(remainingTime),
                        TimeUnit.MILLISECONDS.toSeconds(remainingTime) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remainingTime)));

                Log.v(LOGTAG, "Formatted start time : " + formatTimeStart);
                Log.v(LOGTAG, "Formatted end time : " + formatTimeEnd);

                startTime.setText(formatTimeStart);
                endTime.setText(formatTimeEnd);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    public void playPreviousTrack(View view){

        mediaPlayer.reset();

        if(playTrack == 0) {
            playTrack = trackList.size() - 1;
        } else {
            playTrack = playTrack - 1;
        }

        init(playTrack);
    }

    public void playNextTrack(View view){

        mediaPlayer.reset();

        if(playTrack == trackList.size() - 1) {
            playTrack = 0;
        } else {
            playTrack = playTrack + 1;
        }

        init(playTrack);
    }

    public void playOrPause(View view){

        if(mediaPlayer.isPlaying()) {
            playPause.setImageResource(android.R.drawable.ic_media_play);
            mediaPlayer.pause();
        } else {
            playPause.setImageResource(android.R.drawable.ic_media_pause);
            mediaPlayer.start();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_music_player, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        mediaPlayer.start();
        seekBarHandler.postDelayed(seekBarUpdate, 50);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mediaPlayer.release();
        mediaPlayer = null;

        wifiLock.release();
    }
}

0 个答案:

没有答案