Android音乐播放器即服务并在UI上显示标题曲目,专辑图像

时间:2014-01-10 05:03:47

标签: android service android-activity

我试图在android中编写音乐播放器代码。我想显示歌曲,艺术家和专辑图像的当前标题。     活动是:     包com.example.getmusic;

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


import com.example.getmusic.PlayMusicService.LocalBinder;




import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class GetMusic extends Activity implements OnGestureListener {
      static Handler seekhandler=new Handler();
      boolean isServiceConnected=false;
      PlayMusicService playServ;
     static  TextView tv1,tv2,tv3;
    Button previous,next;static ImageView img;static GestureDetector gDetector;
    int pausePressed=1;static SeekBar sb;

    int currentIndex=0;Cursor cursor;GenericSongClass GSC;
    static MediaPlayer mediaPlayer;static int posofaudiotrack;
    private ServiceConnection conn=new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            isServiceConnected=false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub

    LocalBinder binder=(LocalBinder)service;
    playServ=binder.getService();
    isServiceConnected=true;

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_music);
        gDetector= new GestureDetector(this);
        tv1=(TextView)findViewById(R.id.textView1);
        tv2=(TextView)findViewById(R.id.textView2);
        tv3=(TextView)findViewById(R.id.textView3);
        getSongs();

        img=(ImageView)findViewById(R.id.imageView1);
        sb=(SeekBar)findViewById(R.id.seekBar1);
        try{
        Intent serv = new Intent(this,PlayMusicService.class);

            bindService(serv, conn, Context.BIND_AUTO_CREATE);
        System.out.println("in try calling service");
        startService(serv);
        }
        catch(Exception e){
            System.out.println("Exception is"+e);
        }
        System.out.println("after binding");
        /* 
        try {
            playSong(0);


    }
        catch(Exception e){
        System.out.println("Exception is"+e);
    }*/
         //PlayMusic p=new PlayMusic();
        // p.execute();

    }


    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
         if (isServiceConnected) {
                unbindService(conn);
                isServiceConnected = false;
            }
    }


    public static void mediaPlayerPause()
    {

        if(mediaPlayer!=null)
        {

            mediaPlayer.pause();
            posofaudiotrack=mediaPlayer.getCurrentPosition();
        }

    }
    public void mediaPlayerResume()
    {

        if(mediaPlayer!=null&&!mediaPlayer.isPlaying())
        {
            mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
            mediaPlayer.start();
        }
    }
    public class PlayMusic  extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            getSongs();
            return null;
        }

    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
    }

    public static ArrayList<GenericSongClass> songs = null;

    public void getSongs() {        

        Toast.makeText(getApplicationContext(), "in BindAllSongs()", Toast.LENGTH_SHORT).show();
            String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
            final String[] projection = new String[] {
                    MediaStore.Audio.Media.DISPLAY_NAME,
                    MediaStore.Audio.Media.ARTIST,

                    MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.COMPOSER,MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ALBUM
                    };
                    final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
                            + " COLLATE LOCALIZED ASC";

                    try {

                        Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;


                       cursor = getBaseContext().getContentResolver().query(uri,
                                projection, selection, null, sortOrder);
                     /*  int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                       String s=cursor.getString(column_index);*/
                      // Toast.makeText(getApplicationContext(), "path is"+s, Toast.LENGTH_SHORT).show();
                      // System.out.println("path is"+s);


                       if (null == cursor) {
                            Log.e("error","cursor is null");
                        // If the Cursor is empty, the provider found no matches
                        } else if (cursor.getCount() < 1) {

                            Log.i("info","cursor count<1");
                        } else {



                            songs = new ArrayList<GenericSongClass>(cursor.getCount());
                            cursor.moveToFirst(); 
                            int colIndex=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                            String path = cursor.getString(colIndex);
                           // Toast.makeText(getApplicationContext(), "PATH IS"+path, Toast.LENGTH_SHORT).show();
                            System.out.println("PATH IS"+path);
                            while (!cursor.isAfterLast()) { 
                                GSC = new GenericSongClass();
                                GSC.songTitle = cursor.getString(0);
                                GSC.songArtist = cursor.getString(1);   
                                GSC.songData = cursor.getString(2);
                                GSC.songComposer=cursor.getString(3);
                                GSC.title=cursor.getString(4);
                                GSC.album=cursor.getString(5);

                                songs.add(GSC);
                                cursor.moveToNext();

                            }


                         //   Toast.makeText(getApplicationContext(), "songs first is"+songs.get(0).songTitle, Toast.LENGTH_SHORT).show();
                         //   Toast.makeText(getApplicationContext(), "songs length is"+songs.size(), Toast.LENGTH_SHORT).show();
                           mediaPlayer=new MediaPlayer();
                            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    // TODO Auto-generated method stub
                                     Log.e("I", "Media player has been loaded to memory !");
                                }
                            });
                            /*for(int i=0;i<songs.size();i++){
                                if(mediaPlayer.isPlaying())
                                    mediaPlayer.reset();
                                String p=songs.get(i).songData;
                                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);*/


                        }
                    }
                        catch (Exception ex) {
                      Toast.makeText(getApplicationContext(), "exception is"+ex, Toast.LENGTH_SHORT).show();
                      Log.i("ex is",ex.toString());
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }}
                    }



    protected void getPreviousSong()
    {

        if(currentIndex==0)
            currentIndex=songs.size()-1;
        else{
            currentIndex=currentIndex-1;
            }
        playSong(currentIndex);
    }
    protected void getNextSong() {
        // TODO Auto-generated method stub

        if(currentIndex == songs.size()-1){
            currentIndex=0;

        }
        else
        {
            currentIndex=currentIndex+1;


        }
        playSong(currentIndex);
    }
    private void playSong(int index) {
        // TODO Auto-generated method stub
        try{
            mediaPlayer.reset();
            String p=songs.get(index).songData;
        System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      tv1.setText(songs.get(index).title);
      tv2.setText(songs.get(index).album);
      tv3.setText(songs.get(index).songArtist);
     // tv3.append(songs.get(index).album);
        mediaPlayer.setDataSource(p);
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        byte[] rawArt;
        Bitmap art = null;
        BitmapFactory.Options bfo=new BitmapFactory.Options();
      mmr.setDataSource(p);

        rawArt = mmr.getEmbeddedPicture();



        if (null != rawArt) 
            art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
        img.setImageBitmap(art);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
            Log.d("exc","exception is"+e.toString());
            System.out.println("exception is"+e.toString());
        }
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
            System.out.println("exception is"+e.toString());
        }

        mediaPlayer.start();
        sb.setMax(mediaPlayer.getDuration());
        seekUpdation();
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            seekhandler.removeCallbacks(run);
            mediaPlayer.seekTo(seekBar.getProgress());
            seekhandler.postDelayed(run, 1000);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
                seekhandler.removeCallbacks(run);

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub

            }
        });
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // TODO Auto-generated method stub
                pausePressed=1;
                playServ.getNextSong();

            }
        });

                    }



     Runnable run = new Runnable() {

            @Override
            public void run() {
                seekUpdation();
            }
        };


        public void seekUpdation() {

            sb.setProgress(mediaPlayer.getCurrentPosition());
            seekhandler.postDelayed(run, 1000);
        }
    public class GenericSongClass {

            String songTitle = "";
            String songArtist = "";
            String songData = "";
            String songComposer="";
            String title="";
            String album="";
            String isChecked = "false";
    }



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

    @Override
    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent me) {
    return gDetector.onTouchEvent(me);
    }
    @Override
    public boolean onFling(MotionEvent start, MotionEvent finish, float velocityX,
            float velocityY) {
        pausePressed=1;//int x=playServ.getCurrentIndex();
        // TODO Auto-generated method stub
        if(start.getRawX() < finish.getRawX())
        {
            //Toast.makeText(getApplicationContext(), "chanegd", Toast.LENGTH_SHORT).show();
            if(playServ!=null){

            /*  if(x==0)
                    x=songs.size()-1;
                else{
                    x=currentIndex-1;
                    }
                  tv1.setText(songs.get(x).title);
                  tv2.setText(songs.get(x).album);
                  tv3.setText(songs.get(x).songArtist);
                 tv3.append(songs.get(x).album);*/

            playServ.getPreviousSong();}
            else
                System.out.println("ms null");
        }
        else if(start.getRawX()>finish.getRawX())
        {
            //Toast.makeText(getApplicationContext(), "changed on other", Toast.LENGTH_SHORT).show();

            Log.d("onFLing","in onFling");
            if(playServ!=null){
                /*
                if(x == songs.size()-1){
                    x=0;

                }
                else
                {
                    x=x+1;


                }
                  tv1.setText(songs.get(x).title);
                  tv2.setText(songs.get(x).album);
                  tv3.setText(songs.get(x).songArtist);
                 tv3.append(songs.get(x).album);*/
            playServ.getNextSong();
            }
            else
                System.out.println("ms null");
        }
        return true;

    }

    @Override
    public void onLongPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
            float distanceY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
    System.out.println("PAUSEPRESSED"+pausePressed);
        if(pausePressed==1){
            pausePressed=0;
            playServ.mediaPlayerPause();
        }else if(pausePressed==0){
            pausePressed=1;


                //mediaPlayer.seekTo(posofaudiotrack);
                playServ.mediaPlayerResume();


        }
        return true;
    }

}
and the Service is:
package com.example.getmusic;

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

import com.example.getmusic.GetMusic.GenericSongClass;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class PlayMusicService extends Service{
    MediaPlayer mp;int currentIndex=0;
    ArrayList<GenericSongClass> songs=GetMusic.songs;int pausePressed=1;
    IBinder servbind=new LocalBinder();
    public class LocalBinder extends Binder{
        PlayMusicService getService()
        {
            return PlayMusicService.this;
        }
    }
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return servbind;
    }


    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mp=new MediaPlayer();
        mp.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer arg0) {
                // TODO Auto-generated method stub
                System.out.println("in onPrepared");
            }
        });
mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // TODO Auto-generated method stub
                pausePressed=1;
                getNextSong();
            }
        });
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
      System.out.println("in try");
      playSong(0);
 }
 catch(Exception e){
      System.out.println("in catch and exception is "+e.getMessage());
 }

    }

    public void playSong(int index){

        // TODO Auto-generated method stub
        try{
            System.out.println("in playsong");
            mp.reset();
            String p=songs.get(index).songData;
        System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
     GetMusic.tv1.setText(songs.get(index).title);
GetMusic.tv2.setText(songs.get(index).album);
    GetMusic.tv3.setText(songs.get(index).songArtist);
    GetMusic.tv3.append(songs.get(index).album);
        mp.setDataSource(p);
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        byte[] rawArt;
        Bitmap art = null;
        BitmapFactory.Options bfo=new BitmapFactory.Options();
      mmr.setDataSource(p);

        rawArt = mmr.getEmbeddedPicture();



        if (null != rawArt) 
            art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
    GetMusic.img.setImageBitmap(art);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
            Log.d("exc","exception is"+e.toString());
            System.out.println("exception is"+e.toString());
        }
        try {
            mp.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
            System.out.println("exception is"+e.toString());
        }

        mp.start();
        GetMusic.sb.setMax(mp.getDuration());
        seekUpdation();
GetMusic.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            GetMusic.seekhandler.removeCallbacks(run);
            mp.seekTo(seekBar.getProgress());
            GetMusic.seekhandler.postDelayed(run, 1000);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
                GetMusic.seekhandler.removeCallbacks(run);

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // TODO Auto-generated method stub

            }
        });



    }
     Runnable run = new Runnable() {

            @Override
            public void run() {
                seekUpdation();
            }
        };
     public void seekUpdation() {

            GetMusic.sb.setProgress(mp.getCurrentPosition());
            GetMusic.seekhandler.postDelayed(run, 1000);
        }
    public int getCurrentIndex(){
        return currentIndex;
    }

    public void mediaPlayerPause()
    {

        if(mp!=null)
        {

            mp.pause();
            //pos=mediaPlayer.getCurrentPosition();
        }

    }
    public void mediaPlayerResume()
    {

        if(mp!=null&&!mp.isPlaying())
        {
            mp.seekTo(mp.getCurrentPosition());
            mp.start();
        }
    }
    public void getPreviousSong()
    {

        if(currentIndex==0)
            currentIndex=songs.size()-1;
        else{
            currentIndex=currentIndex-1;
            }
        playSong(currentIndex);
    }
    public void getNextSong() {
        // TODO Auto-generated method stub

        if(currentIndex == songs.size()-1){
            currentIndex=0;
        }
        else
        {
            currentIndex=currentIndex+1;


        }
        playSong(currentIndex);
    }


    @Override   
    public int onStartCommand(Intent intent, int flags, int startId) 
    {   
        mp.start(); 

        return 0;

    }

    @Override   
    public void onDestroy() 
    {   
        mp.release();       
        super.onDestroy();

    }

}

问题在于它有时打得很好,当我们按下后退按钮或在主屏幕上轻扫其他应用程序时,它会停止。我想在UI上显示标题轨道,图像。但是这段代码显示某些歌曲的错误图像对于某些人来说,即使图像存在,它甚至都不会显示图像。在按下后屏幕之后,当我们使用其他应用程序并回到此时它只显示TextView和正常的android图像。是否需要重新创建活动?我们可以调用吗?服务的活动方法?如何解决问题?请帮帮我。

1 个答案:

答案 0 :(得分:0)

您需要背景音乐服务并与活动进行通信以及服务的消息或绑定活动,而不是从服务调用活动方法,这将导致跨进程问题。

我实际上从我写过的商业项目中开源了一个带有后台服务Lyric的音乐播放器,你可以看一下:https://github.com/Wangchao0721/MusicPlayer

但我没有时间填写自述文件,只需查看活动包中的MediaPlayerActivity.java,您就会知道如何使用它。