2019-08-22Service音乐播放器

清单文件加权限

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Mainactivity代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView name;
    private Button last;
    private Button play;
    private Button stop;
    private Button next;
    private static SeekBar progress;
    private RelativeLayout bottom;
    private Button bendi;
    private RelativeLayout top;
    private ListView listview;
    private List<Music> list;
    private ServiceConnection connection;
    private Button just_one;
    private static MyMusicService.MusicBiner biner;

    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 111) {
                int i = msg.arg1;
                progress.setProgress(i);
            } else if (msg.what == 810) {
                biner.callpause();
            }
            else if (msg.what == 820) {
                biner.callrestart();
            }
            else if (msg.what == 830) {
                biner.calllast();
            }
            else if (msg.what == 840) {
                biner.callnext();
            }
            else if (msg.what == 728) {
                biner.callnext();
            }
        }
    };

    @TargetApi(Build.VERSION_CODES.M)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        requestPermissions(new String []{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
        list = MusicUtils.getlist(this);
        initView();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.notify.pause");
        intentFilter.addAction("com.notify.play");
        intentFilter.addAction("com.notify.last");
        intentFilter.addAction("com.notify.next");
        MyReceiver myReceiver = new MyReceiver();
        registerReceiver(myReceiver, intentFilter);

        Intent intent1 = new Intent(MainActivity.this, MyMusicService.class);
        startService(intent1);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                biner.callplay(i);
                progress.setMax((int) list.get(i).getDuration());
            }
        });

        //启动
        Intent intent = new Intent(this, MyMusicService.class);
        startService(intent);

        connection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                biner = (MyMusicService.MusicBiner) iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        bindService(intent, connection, Service.BIND_AUTO_CREATE);

        progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
                    biner.callseek(i);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(connection!=null){
            unbindService(connection);
        }
    }

    private void initView() {
        name = (TextView) findViewById(R.id.name);
        last = (Button) findViewById(R.id.last);
        play = (Button) findViewById(R.id.play);
        stop = (Button) findViewById(R.id.stop);
        next = (Button) findViewById(R.id.next);
        progress = (SeekBar) findViewById(R.id.progress);
        bottom = (RelativeLayout) findViewById(R.id.bottom);
        bendi = (Button) findViewById(R.id.bendi);
        top = (RelativeLayout) findViewById(R.id.top);
        listview = (ListView) findViewById(R.id.listview);

        last.setOnClickListener(this);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        bendi.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.last:
                biner.calllast();
                break;
            case R.id.play:
                biner.callrestart();
                break;
            case R.id.stop:
                biner.callpause();
                break;
            case R.id.next:
                biner.callnext();
                break;
            case R.id.bendi:
                MyAdapter myAdapter = new MyAdapter(list, MainActivity.this);
                listview.setAdapter(myAdapter);
                break;
        }
    }
}

Main布局代码

<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"
    android:padding="20dp"
    >

    <RelativeLayout
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minLines="1" />
        <Button
            android:id="@+id/last"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="last"
            />
        <Button
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/last"
            android:text="play"
            />
        <Button
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/play"
            android:text="stop"
            />

        <Button
            android:id="@+id/next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/stop"
            android:layout_centerVertical="true"
            android:text="next"
            />

        <SeekBar
            android:id="@+id/progress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/play"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/bendi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="加载本地音乐"
            />
        <Button
            android:id="@+id/just_one"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="单曲循环"
            android:layout_alignParentRight="true"
            />

    </RelativeLayout>
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/top"
        android:layout_above="@id/bottom"
        />

</RelativeLayout>

musiclayout代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    >

    <TextView
        android:id="@+id/music_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="未知歌曲"/>
    <TextView
        android:id="@+id/person_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/music_name"
        android:textSize="16dp"
        android:text="未知歌手"/>
    <TextView
        android:id="@+id/music_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:textSize="18dp"
        android:text="歌曲时长"/>
</RelativeLayout>

notificationlayout代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="0dp">
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/Button_pause_Broad"
            android:text="暂停"
            />
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/Button_restart_Broad"
            android:text="继续播放"
            />
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/Button_last_Broad"
            android:text="上一首"
            />
        <Button
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/Button_next_Broad"
            android:text="下一首"
            />

    </LinearLayout>
</LinearLayout>

Music实体类

public class Music {
    private String title;
    private String artist;
    private String data;
    private long duration;
    private int size;
    private int position;

    public Music(String title, String artist, String data, long duration, int size, int position) {
        this.title = title;
        this.artist = artist;
        this.data = data;
        this.duration = duration;
        this.size = size;
        this.position = position;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}

Music工具类

public class MusicUtils {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static List<Music> getlist(Context context) {
        List<Music> list = new ArrayList<>();
        int position = 0;
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                int size = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
                position++;
                Music music = new Music(title, artist, data, duration, size, position);
                list.add(music);
            }
            cursor.close();
            return list;
        } else {
            Toast.makeText(context, "没有资源", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

}

适配器代码

public class MyAdapter extends BaseAdapter {
    private List<Music> list;
    private LayoutInflater layoutInflater;
    private Context context;

    public MyAdapter(List<Music> list, Context context) {
        this.list = list;
        this.context = context;
        layoutInflater=LayoutInflater.from(context);
    }

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

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if(view==null){
            view = layoutInflater.inflate(R.layout.musiclayout, null);
            viewHolder=new ViewHolder();
            viewHolder.first=view.findViewById(R.id.music_name);
            viewHolder.second=view.findViewById(R.id.person_name);
            viewHolder.third=view.findViewById(R.id.music_time);
            view.setTag(viewHolder);
        }
        else{
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.first.setText(list.get(i).getTitle());
        viewHolder.second.setText(list.get(i).getArtist());
        long duration = list.get(i).getDuration();
        long fen=duration/60000;
        long miao=(duration%60000)/1000;
        viewHolder.third.setText(fen+"分"+miao+"秒");
        return view;
    }
    class ViewHolder{
        TextView first,second,third;
    }
}

服务代码

public class MyMusicService extends Service {
    private MediaPlayer mediaPlayer;
    private List<Music> list;
    private int index;
    private Handler handler = new Handler();
    private Notification.Builder builder;

    public MyMusicService() {

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        list = MusicUtils.getlist(getApplicationContext());
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        MusicBiner musicBiner = new MusicBiner();
        return musicBiner;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        RemoteViews views = new RemoteViews(getPackageName(), R.layout.notificationlayout);

        //第一个按钮的点击逻辑
        /**
         * 通过一个PendingIntent 发送一个intent.
         * getBroadcast的方法是跳往广播的一个intent.
         * getBroadcast的参数,1,上下文,2是请求码唯一即可,3,intent对象,4,PendingIntent的创建方式.
         * setOnClickPendingIntent.这个方法可以给组件设置一个点击事件.参数:1,组件id,2pendingIntent对象
         * 也就是点击以后要跳转到何方.
         */
        Intent intent1 = new Intent();
        intent1.setAction("com.notify.pause");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 150, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.Button_pause_Broad, pendingIntent);

        Intent intent2 = new Intent();
        intent2.setAction("com.notify.play");
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 160, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.Button_restart_Broad, pendingIntent2);

        Intent intent3 = new Intent();
        intent3.setAction("com.notify.last");
        PendingIntent pendingIntent3 = PendingIntent.getBroadcast(this, 170, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.Button_last_Broad, pendingIntent3);

        Intent intent4 = new Intent();
        intent4.setAction("com.notify.next");
        PendingIntent pendingIntent4 = PendingIntent.getBroadcast(this, 180, intent4, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.Button_next_Broad, pendingIntent4);
        //设置通知的布局
        builder.setContent(views);
//        builder.setCustomContentView(views);
        //开始一个前台服务
        startForeground(1, builder.build());
        return super.onStartCommand(intent, flags, startId);
    }

    public class MusicBiner extends Binder {
        public void callplay(int position) {
            playmusic(position);
            index = position;
        }

        public void callpause() {
            pause();
        }

        public void callrestart() {
            restart();
        }

        public void calllast() {
            last();
        }

        public void callnext() {
            next();
        }

        public void callseek(int i) {
            seek(i);
        }

    }

    public void seek(int i) {
        mediaPlayer.seekTo(i);
    }

    public void next() {
        if (++index > list.size() - 1) {
            index = 0;
        }
        playmusic(index);
    }

    public void last() {
        if (--index < 0) {
            index = list.size() - 1;
        }
        playmusic(index);
    }

    public void restart() {
        mediaPlayer.start();
    }

    public void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }

    public void playmusic(final int position) {
        mediaPlayer.reset();
        Music music = list.get(position);
        try {
            mediaPlayer.setDataSource(music.getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(final MediaPlayer mediaPlayer) {
                    mediaPlayer.start();

                    Timer timer = new Timer();//定时器 走进度条
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            int currentPosition = mediaPlayer.getCurrentPosition();
                            Message message = Message.obtain();
                            message.arg1 = currentPosition;
                            message.what = 111;
                            MainActivity.handler.sendMessage(message);
                            if(currentPosition==mediaPlayer.getDuration()){
                                    MainActivity.handler.sendEmptyMessage(728);
                            }
                        }
                    }, 0, 1000);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

广播代码

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i("TAG","进来了广播");
        if(action.equals("com.notify.pause")){
            MainActivity.handler.sendEmptyMessage(810);
        }
        else if(action.equals("com.notify.play")){
            MainActivity.handler.sendEmptyMessage(820);
        }
        else if(action.equals("com.notify.last")){
            MainActivity.handler.sendEmptyMessage(830);
        }
        else if(action.equals("com.notify.next")){
            MainActivity.handler.sendEmptyMessage(840);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,029评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,238评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,576评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,214评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,324评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,392评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,416评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,196评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,631评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,919评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,090评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,767评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,410评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,090评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,328评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,952评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,979评论 2 351

推荐阅读更多精彩内容