Day0823_将音乐库中的音乐在Service中异步加载, 播放音乐并设置到通知栏

来源:互联网 发布:php运费模板源码 编辑:程序博客网 时间:2024/05/17 03:33
MyService类
package com.kangdi.day0823_service_hunhe;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.media.MediaPlayer;import android.os.Binder;import android.os.IBinder;import android.widget.RemoteViews;import java.io.IOException;import java.util.List;public class MyService extends Service implements ICallBack, MediaPlayer.OnPreparedListener {    private MusicProvider musicProvider;    private IActivityCallBack iActivityCallBack;    private String MUSIC_START = "playMusic";    private String MUSIC_CLOSE = "close";    private List<Music> list;    /**设置接口*/    public void setiActivityCallBack(IActivityCallBack iActivityCallBack) {        this.iActivityCallBack = iActivityCallBack;    }    @Override    public void onCreate() {        musicProvider = new MusicProvider(this);        /**当在Activity中调用startService后调用该方法*/        /**注册该接口*/        musicProvider.setiCallBack(this);    }    /** 当异步加载所有数据之后调用该方法给list赋值*/    @Override    public void myCallBack(List<Music> list) {        this.list = list;        /**当回调该接口时调用注册给Acitivity的接口*/        iActivityCallBack.activityCallBack(list);    }    /**开始音乐*/    @Override    public void onPrepared(MediaPlayer mp) {        if (mp == null) {            return;        }        mp.start();    }    /**创建Binder的实现类 用于在Acitivty中获得Myservice对象*/    class MyBinder extends Binder{        public MyService getMyService(){            return MyService.this;        }    }    private MediaPlayer mPlayer;    /**创建MediaPlayer对象并启动*/    private void creatMediaIfNeeded(){        if (mPlayer==null){            mPlayer = new MediaPlayer();            /**MediaPlayer注册监听 , 当加载数据之后调用该方法*/            mPlayer.setOnPreparedListener(this);        }else{            /**MediaPlayer对象存在时 调用reset方法*/            mPlayer.reset();        }    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        /**IntentAcitivy中传入的Intent是执行 播放音乐操作*/        if (MUSIC_START.equals(intent.getStringExtra("actionKey"))){            int position = intent.getIntExtra("positionKey",0);            processPlayRequest(position);        }else if (MUSIC_CLOSE.equals(intent.getStringExtra("buttonKey"))){            /**Intent是通知栏中的按钮 停止Servcie*/            stopSelf();        }        return super.onStartCommand(intent,flags,startId);    }    private void processPlayRequest(int position) {        creatMediaIfNeeded();        Music m = list.get(position);        try {            /**设置数据源*/            mPlayer.setDataSource(m.getData());            /**异步加载数据*/            mPlayer.prepareAsync();        } catch (IOException e) {            e.printStackTrace();        }        createNotification(m);    }    /**声明NotificationManager变量*/    private NotificationManager nManager;    private void createNotification(Music music) {        /**新建 通知栏布局的View RemoteViews*/        RemoteViews rViews = new RemoteViews(getPackageName(),R.layout.notification_item);        /**设置布局中的内容*/        rViews.setTextViewText(R.id.textView1,"Abc");        rViews.setTextViewText(R.id.textView2,music.getArtist());        /**设置意图*/        Intent sIntent = new Intent(this,MyService.class);        sIntent.putExtra("buttonKey","close");        /**设置布局中按钮的点击事件         * 第一个参数 按钮的ID         * 第二个参数 PenddingIntent对象 , 需要Context 请求码 意图 常量(下面声明的常量是最常用的)         * */        rViews.setOnClickPendingIntent                (R.id.button, PendingIntent.getService(this,100,sIntent,PendingIntent.FLAG_UPDATE_CURRENT));        /**利用获取系统服务 来获取NotificationManager对象*/        nManager  = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        /**利用Notification内部类Builder创建 Notification对象         * setSmallIcon 设置通知栏里的图标         * setContent 设置通知栏里的布局         * build方法 设置通知*/        Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)                .setContent(rViews).build();        /**利用NotificationManager对象 发出通知*/        nManager.notify(0,notification);        /**service绑定到一个前台通知(相当于service的一个前台界面 , 进程优先级高 不容易被kill)*///        startForeground(0,notification);    }    @Override    public void onDestroy() {        /**如果将通知设置为前台通知需要把停止*///        stopForeground(true);        nManager.cancel(0);        if (mPlayer!=null){            mPlayer.release();            mPlayer=null;        }    }    @Override    public IBinder onBind(Intent intent) {        musicProvider.loadMusic();        return new MyBinder();    }}
MusicProvider类
public class MusicProvider {    private ContentResolver contentResolver;    private Context mContext;    public MusicProvider(Context context){        mContext = context;    }    ICallBack iCallBack;    /**设置接口*/    public void setiCallBack(ICallBack iCallBack){        this.iCallBack = iCallBack;    }    public void loadMusic() {        /**异步加载音乐库中的音乐*/        new AsyncTask<Void, Void, List<Music>>() {            @Override            protected List<Music> doInBackground(Void... params) {                contentResolver=mContext.getContentResolver();                List<Music> list = new ArrayList<>();                Cursor query = contentResolver.query(Media.EXTERNAL_CONTENT_URI,                        null,                        Media.IS_MUSIC + "=?", new String[]{"1"}, null);                while(query.moveToNext()) {                    list.add(new Music(                            query.getString(query.getColumnIndex(Media.DISPLAY_NAME)),                            query.getString(query.getColumnIndex(Media.DATA))                            , query.getString(query.getColumnIndex(Media.ARTIST))                    ));                }                query.close();                return list;            }            /**加载完数据后回调该接口*/            @Override            protected void onPostExecute(List<Music> musics) {                if (iCallBack==null)return;                iCallBack.myCallBack(musics);            }        }.execute();    }}
MainActivity类
public class MainActivity extends AppCompatActivity implements ServiceConnection, IActivityCallBack {    private ListView listView;    private MyService myService;    private MusicAdapter musicAdapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView = (ListView) findViewById(R.id.listView);        /**绑定Service 第三个参数会自动创建Service 即调用Service的生命周期方法 onCreate()*/        bindService(new Intent(this,MyService.class),this,BIND_AUTO_CREATE);        listView.setOnItemClickListener(new OnItemClickListener() {            /**当点击ListViewItemstartService 并在 Intent 传入 position             * startService(调用之后) 会在MyService调用 onStartCommand()方法             * onStartCommand()方法中获取传入的position*/            @Override            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                Intent intent = new Intent(MainActivity.this,MyService.class);                intent.putExtra("actionKey","playMusic");                intent.putExtra("positionKey",position);                startService(intent);            }        });    }    @Override    public void onServiceConnected(ComponentName name, IBinder service) {        /**获得MyService对象*/        myService = ((MyService.MyBinder) service).getMyService();        /**注册该接口*/        myService.setiActivityCallBack(this);    }    /**Service不正常关闭时会调用此方法*/    @Override    public void onServiceDisconnected(ComponentName name) {    }    /**MyService回调myCallBack方法后调用该方法*/    /**在这里设置listView*/    @Override    public void activityCallBack(List<Music> list) {        musicAdapter = new MusicAdapter(MainActivity.this,R.layout.listview_item,list);        listView.setAdapter(musicAdapter);    }    @Override    protected void onDestroy() {        /**在销毁Activity时与MyService解除绑定*/        super.onDestroy();        unbindService(this);    }}

1 1
原创粉丝点击