Service后台音乐播放器

Seriver案例后台音乐播放器

    • 案例

案例

音乐播放器
先初始化音乐列表
需要添加权限

在这里插入图片描述

获取音频




uri:MediaStore.Audio.Media.EXTERNAL_CONTENT_URI 
字段:MediaStore.Audio.Media.TITLE歌名 
	  MediaStore.Audio.Media.ARTIST歌手 
 	 MediaStore.Audio.Media.DURATION总时长 
  	MediaStore.Audio.Media.DATA地址

Service后台音乐播放器_第1张图片

Service后台音乐播放器_第2张图片

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

 <ListView
     android:layout_above="@id/ll"
     android:id="@+id/lv"
     android:layout_width="match_parent"
     android:layout_height="match_parent"></ListView>
 <LinearLayout
     android:id="@+id/ll"
     android:layout_alignParentBottom="true"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">

  <ImageView
      android:onClick="shangyishou"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/zjiantou"
      />
  <Button

      android:onClick="bofang"
      android:id="@+id/button"

      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="播放"
      />
  <Button
      android:onClick="tingzhi"
      android:layout_toRightOf="@id/button"
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="停止"
      />

  <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/jiantou"
      android:onClick="xiayishou"
      />
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/name"
      />
 </LinearLayout>

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


    <LinearLayout
        android:orientation="vertical"
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tname"
        />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tphone"
            />
        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />




    </LinearLayout>


</RelativeLayout>
package com.example.muscikplayqi;

import android.app.Service;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {
  static   ArrayList<Musick> musicks;
    Myservice myservice;
    TextView textView;
    TextView textView1;

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myservice = ((Myservice.MyBinder) service).getservice();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView1=findViewById(R.id.name);
        textView=findViewById(R.id.name);
        listView = findViewById(R.id.lv);
        ContentResolver contentResolver = getContentResolver();

        Cursor query = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null, null);

         musicks = new ArrayList<>();
        while (query.moveToNext()) {
            String string = query.getString(query.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String string1 = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            long aLong = query.getLong(query.getColumnIndex(MediaStore.Audio.Media.DURATION));
            String time = getTime(aLong);
            String string2 = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DATA));
            Musick musick = new Musick(string, string1, time, string2);
            musicks.add(musick);
        }
        for (Musick s : musicks) {
            Log.e("####", "onCreate: " + s.toString());
        }

        Intent intent = new Intent(this, Myservice.class);
        bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);


        listView.setAdapter(new MyBaseadpter(MainActivity.this, musicks));

    }

    public String getTime(long l) {
        long sum = l / 1000;
        int f = (int) (sum / 60);
        int m = (int) (sum % 60);
        String f1 = f + "";
        String f2 = m + "";
        if (f < 10) {
            f1 = 0 + "" + f;
        }
        if (m < 10) {
            f2 = 0 + "" + m;
        }
        return f1 + ":" + f2;
    }

    public void bofang(View view) {
        try {
            Musick musick = musicks.get(0);
            myservice.play(musicks);
            textView1.setText(musicks.get(Share.flag).name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    public void tingzhi(View view) {
        myservice.tingzhi();
    }

    public void shangyishou(View view) {
        myservice.rec();
        textView1.setText(musicks.get(Share.flag).name);
    }

    public void xiayishou(View view) {
        myservice.next();
        textView1.setText(musicks.get(Share.flag).name);
    }
}

package com.example.muscikplayqi;

public class Musick {

    String name;
    String singer;
    String time;
    String address;

    public Musick(String name, String singer, String time, String address) {
        this.name = name;
        this.singer = singer;
        this.time = time;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Musick{" +
                "name='" + name + '\'' +
                ", singer='" + singer + '\'' +
                ", time=" + time +
                ", address='" + address + '\'' +
                '}';
    }
}

package com.example.muscikplayqi;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class MyBaseadpter extends BaseAdapter {
    Context context;
    ArrayList<Musick> getjson ;


    public MyBaseadpter(Context context, ArrayList<Musick> getjson) {
        this.context = context;
        this.getjson = getjson;
    }

    @Override
    public int getCount() {
        return getjson.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHodler viewHodler;
        if(convertView==null){
            viewHodler=new ViewHodler();

            convertView=View.inflate(context,R.layout.sim,null);
            viewHodler.textView1=convertView.findViewById(R.id.tname);
            viewHodler.textView2=convertView.findViewById(R.id.tphone);
            viewHodler.textView3=convertView.findViewById(R.id.time);

            convertView.setTag(viewHodler);

        }else{
            viewHodler = (ViewHodler) convertView.getTag();
        }
        if(viewHodler!=null){

            Musick musick = getjson.get(position);

            viewHodler.textView1.setText(musick.name);
            viewHodler.textView2.setText(musick.singer);
            viewHodler.textView3.setText(musick.time);

        }


        return convertView;
    }
    class ViewHodler{

        TextView textView1;
        TextView textView2;
        TextView textView3;


    }
}

package com.example.muscikplayqi;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

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



public class Myservice extends Service {

    MediaPlayer mediaPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public  void play(ArrayList<Musick> musicks) throws IOException {
        Musick musick = musicks.get(Share.flag);
        if(mediaPlayer==null){
            mediaPlayer=new MediaPlayer();
            mediaPlayer.setDataSource(musick.address);
            mediaPlayer.prepare();
            mediaPlayer.start();
        }else{
            mediaPlayer.start();
        }

    }

    public void tingzhi(){
        if(mediaPlayer!=null){
            mediaPlayer.pause();
        }
   }
    public void stop() {
        if(mediaPlayer!=null){
            mediaPlayer.stop();//暂停音乐
            mediaPlayer.release();//资源释放
            mediaPlayer=null;//设置为null
        }
    }

   public void next(){
       stop();
        if(Share.flag+1<MainActivity.musicks.size()){
            Share.flag++;
            try {
                play(MainActivity.musicks);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            Share.flag=0;
            try {
                play(MainActivity.musicks);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
   }
    public void rec(){
        stop();
        if(Share.flag-1<0){

            Share.flag=MainActivity.musicks.size()-1;
            try {
                play(MainActivity.musicks);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{
            Share.flag--;

            try {
                play(MainActivity.musicks);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    class MyBinder extends Binder{
        public Myservice getservice(){
            return Myservice.this;
        }
    }
}

package com.example.muscikplayqi;

public class Share {

   static int flag=0;
}

记得要注册清单文件的service哦

你可能感兴趣的:(Android四大组件)