Android開發之本地音樂播放器(簡單粗暴版)

  • 本程序爲直接在Activity中計算並更新後臺服務音樂播放進度,沒有使用到廣播

  • 在學習廣播之前,艱難的通過這個方法來實現了更新音樂播放進度,不推薦使用,不過感興趣的可以研究一下。

  • 大概的思路就是通過異步任務類來模擬耗時操作,然後計算出開始播放的時間與當前時間的差,然後跟音樂的總時間相比得到ProgressBar的進度,然後每一秒更新一次。

  • 暫停時可以將暫停的時間加到開始時間上,實現無斷點更新

  • 效果圖如下:
    這裏寫圖片描述

  • 主函數代碼:MusicActivity.java

public class MusicActivity extends AppCompatActivity {

    private ListView lv;
    private List lvList;
    private List<Mp3Info> mp3InfoList;
    private ImageButton bt1,bt2;
    private ImageView iv1;
    private TextView tv1,tv2;
    private ProgressBar pb;
    private Boolean flag;
    private int location;
    private long startTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        lv= (ListView) findViewById(R.id.lv);
        bt1= (ImageButton) findViewById(R.id.bt1);
        bt2= (ImageButton) findViewById(R.id.bt2);
        tv1= (TextView) findViewById(R.id.tv1);
        tv2= (TextView) findViewById(R.id.tv2);
        iv1= (ImageView) findViewById(R.id.iv1);
        pb= (ProgressBar) findViewById(R.id.pb);
        location=0;
        flag=false;
        LoadLvList();
        ArrayAdapter aa=new ArrayAdapter(this,android.R.layout.simple_list_item_1,lvList);
        lv.setAdapter(aa);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                location=position;
                setPlay(position);
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MusicActivity.this, MyService.class);
                intent.putExtra("tag",1);
                startService(intent);
                if(flag==true){
                    bt1.setImageResource(R.mipmap.btn_pause);
                    flag=false;
                }else{
                    bt1.setImageResource(R.mipmap.btn_play);
                    flag=true;
                }

            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                location=location+1;
                setPlay(location);
            }
        });

    }

    public void LoadLvList() {
        mp3InfoList=new ArrayList<Mp3Info>();
        mp3InfoList= MediaUtil.getMusicInfo(this);
        lvList=new ArrayList();
        for(int i=0;i<mp3InfoList.size();i++){
            lvList.add(mp3InfoList.get(i).getTitle());
        }
    }

    public void setPlay(int location){
        Intent intent=new Intent(MusicActivity.this, MyService.class);
        Mp3Info mp3Info=mp3InfoList.get(location);
        intent.putExtra("tag",0);
        intent.putExtra("url",mp3Info.getUrl());
        intent.putExtra("id",mp3Info.getId());
        intent.putExtra("title",mp3Info.getTitle());
        intent.putExtra("artist",mp3Info.getArtist());
        intent.putExtra("albumId",mp3Info.getAlbumId());
        startService(intent);
        tv1.setText(mp3Info.getTitle());
        tv2.setText(mp3Info.getArtist());
        Bitmap bitmap = MediaUtil.getArtwork(getBaseContext(), mp3Info.getId(),
                mp3Info.getAlbumId(), true, false);
        iv1.setImageBitmap(bitmap);
        if(flag==false){
            bt1.setImageResource(R.mipmap.btn_play);
            flag=true;
        }
        int duration=(int)mp3Info.getDuration();
        new MyProgress().execute(duration);
    }

    public class MyProgress extends AsyncTask<Integer,Integer,Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            startTime=System.currentTimeMillis();
            pb.setMax(100);
            pb.setProgress(0);
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            int i=0;
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }if(flag==true) {
                    Long currentTime = System.currentTimeMillis();
                    int progress = (int) ((currentTime - startTime) * 100 / params[0]);
                    Log.d("===progress", "" + progress);
                    Log.d("===currentTime", "" + currentTime);
                    Log.d("===startTime", "" + startTime);
                    Log.d("===duration", "" + params[0]);
                    if (progress <= 100) {
                        publishProgress(progress);
                    }
                }else{
                    startTime=startTime+1000;
                    continue;
                }

                if(1000*i>=params[0]){
                    break;
                }
                i++;
            }
            return 0;
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.d("===","更新進度"+values[0]);
            super.onProgressUpdate(values[0]);
            pb.setMax(100);
            pb.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            Log.d("===","異步類執行完畢");
            super.onPostExecute(integer);
            setPlay(location);
        }
    }
}
  • service部分的代碼:MyService.java
public class MyService extends Service {

    private MediaPlayer mediaPlayer;

    private NotificationManager nm;
    private NotificationCompat.Builder builder;
    private Notification nf;


    public MyService() {
    }

    public class MyBind extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    public void test() {
        Log.d("====", "我是Service裏的方法");
        stopSelf();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();

        Log.d("====", "服務創建");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("====", "服務啓動--非綁定方式");
        if(intent!=null){
            int tag=intent.getIntExtra("tag",3);
            switch (tag){
                case 0:
                    String url=intent.getStringExtra("url");
                    String title=intent.getStringExtra("title");
                    String artist=intent.getStringExtra("artist");
                    long id=intent.getLongExtra("id",0);
                    long albumId=intent.getLongExtra("albumId",0);
                    try {
                        if(mediaPlayer!=null){
                            mediaPlayer.reset();
                        }
                        mediaPlayer.setDataSource(this, Uri.parse(url));
                        mediaPlayer.prepare();
                        mediaPlayer.setLooping(true);
                        mediaPlayer.start();
                        showNotification(title,artist,id,albumId);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case 1:
                    if(mediaPlayer!=null){
                        if(mediaPlayer.isPlaying()){
                            mediaPlayer.pause();
                        }else{
                            mediaPlayer.start();
                        }

                    }
                    break;
                default:
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void showNotification(String title, String artist,long id,long albumId) {
        nm= (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
        builder= new NotificationCompat.Builder(getBaseContext());
        RemoteViews contentView=new RemoteViews(getPackageName(),R.layout.notification_music_layout);
        contentView.setTextViewText(R.id.tv1,title);
        contentView.setTextViewText(R.id.tv2,artist);

        Bitmap bitmap = MediaUtil.getArtwork(this, id,
                albumId, true, false);// 獲取專輯位圖對象,爲大圖
        contentView.setImageViewBitmap(R.id.iv1,bitmap);
        builder.setContent(contentView).setSmallIcon(R.mipmap.ic_launcher);
        nf=builder.build();
        nm.notify(0,nf);
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("====", "服務啓動--綁定方式");
        return new MyBind();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("====", "服務啓動--綁定方式--解除綁定");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        Log.d("====", "服務銷燬");
    }

}
  • 佈局代碼(用到的兩個佈局差不多):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ygd.jreduch10.MusicActivity">
    <ListView
        android:id="@+id/lv"
        android:layout_above="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>


    <ProgressBar
        android:id="@+id/pb"
        android:background="#FFFF"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_above="@+id/rl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:id="@+id/rl"
        android:background="#a19f9f"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/iv1"
            android:src="@mipmap/ic_launcher"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_marginLeft="20dp"
            android:id="@+id/tv1"
            android:textSize="20sp"
            android:text="HelloMusic"
            android:textColor="#FFFF"
            android:layout_toRightOf="@+id/iv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/tv2"
            android:layout_marginLeft="20dp"
            android:textColor="#FFFF"
            android:layout_toRightOf="@+id/iv1"
            android:layout_below="@+id/tv1"
            android:text="HelloSinger"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageButton
            android:id="@+id/bt1"
            android:layout_marginRight="20dp"
            android:layout_toLeftOf="@+id/bt2"
            android:src="@mipmap/btn_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageButton
            android:id="@+id/bt2"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:src="@mipmap/btn_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </RelativeLayout>


</RelativeLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章