2019-08-22Service音樂(lè)播放器

清單文件加權(quán)限

 <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());
            }
        });

        //啟動(dòng)
        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="加載本地音樂(lè)"
            />
        <Button
            android:id="@+id/just_one"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="單曲循環(huán)"
            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="歌曲時(shí)長(zhǎng)"/>
</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="繼續(xù)播放"
            />
        <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實(shí)體類

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, "沒(méi)有資源", 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;
    }
}

服務(wù)代碼

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);

        //第一個(gè)按鈕的點(diǎn)擊邏輯
        /**
         * 通過(guò)一個(gè)PendingIntent 發(fā)送一個(gè)intent.
         * getBroadcast的方法是跳往廣播的一個(gè)intent.
         * getBroadcast的參數(shù),1,上下文,2是請(qǐng)求碼唯一即可,3,intent對(duì)象,4,PendingIntent的創(chuàng)建方式.
         * setOnClickPendingIntent.這個(gè)方法可以給組件設(shè)置一個(gè)點(diǎn)擊事件.參數(shù):1,組件id,2pendingIntent對(duì)象
         * 也就是點(diǎn)擊以后要跳轉(zhuǎn)到何方.
         */
        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);
        //設(shè)置通知的布局
        builder.setContent(views);
//        builder.setCustomContentView(views);
        //開(kāi)始一個(gè)前臺(tái)服務(wù)
        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();//定時(shí)器 走進(jìn)度條
                    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","進(jìn)來(lái)了廣播");
        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);
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市谨垃,隨后出現(xiàn)的幾起案子钞楼,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,294評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件趾断,死亡現(xiàn)場(chǎng)離奇詭異寻仗,居然都是意外死亡安寺,警方通過(guò)查閱死者的電腦和手機(jī)弄慰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,493評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門第美,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人曹动,你說(shuō)我怎么就攤上這事斋日。” “怎么了墓陈?”我有些...
    開(kāi)封第一講書人閱讀 157,790評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵恶守,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我贡必,道長(zhǎng)兔港,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 56,595評(píng)論 1 284
  • 正文 為了忘掉前任仔拟,我火速辦了婚禮衫樊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘利花。我一直安慰自己科侈,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,718評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布炒事。 她就那樣靜靜地躺著臀栈,像睡著了一般。 火紅的嫁衣襯著肌膚如雪挠乳。 梳的紋絲不亂的頭發(fā)上权薯,一...
    開(kāi)封第一講書人閱讀 49,906評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音睡扬,去河邊找鬼盟蚣。 笑死,一個(gè)胖子當(dāng)著我的面吹牛卖怜,可吹牛的內(nèi)容都是我干的屎开。 我是一名探鬼主播,決...
    沈念sama閱讀 39,053評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼马靠,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼牍戚!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起虑粥,我...
    開(kāi)封第一講書人閱讀 37,797評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎辣辫,沒(méi)想到半個(gè)月后寇蚊,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體跋选,經(jīng)...
    沈念sama閱讀 44,250評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡裸卫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,570評(píng)論 2 327
  • 正文 我和宋清朗相戀三年彬祖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了茁瘦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,711評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡储笑,死狀恐怖甜熔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情突倍,我是刑警寧澤腔稀,帶...
    沈念sama閱讀 34,388評(píng)論 4 332
  • 正文 年R本政府宣布,位于F島的核電站羽历,受9級(jí)特大地震影響焊虏,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜秕磷,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,018評(píng)論 3 316
  • 文/蒙蒙 一诵闭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧澎嚣,春花似錦疏尿、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,796評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至颈抚,卻和暖如春踩衩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背贩汉。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,023評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工驱富, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人匹舞。 一個(gè)月前我還...
    沈念sama閱讀 46,461評(píng)論 2 360
  • 正文 我出身青樓褐鸥,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親赐稽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子叫榕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,595評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容