day4.23总结_Service绑定和混合模式以及Messager的应用

一、绑定模式的service

绑定模式service相当于在activity端与service端建立了一个长链接(ServiceConnection),然后可以通过此长连接对象中的方法获得Service中返回的绑定对象。通过此对象调用service中的一些业务方法。

 

1)绑定模式service的生命周期方法:

1)onCreate (只执行一次)

2)onBind(只执行一次)

3)onUnbind(只执行一次)

4)onDestory(只执行一次)

 

我们一般要把自己的业务,在service对象的生命周期方法中实现。

例子1:绑定模式service的生命周期

public class MainActivity extends Activity {

private IPlayer player;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

    //绑定service

bindService(newIntent(this,MusicService.class),conn,Context.BIND_AUTO_CREATE);

}

private ServiceConnection conn=new ServiceConnection() {  建立了一个长链接

@Override

public void onServiceDisconnected(ComponentName name) {

}

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

player=(IPlayer)service;                     返回的绑定对象

}

};

public void onPlay(View v){

player.play();

}

public void onPause(View v){

player.pause();

}

 

@Override

protected void onDestroy() {

super.onDestroy();

//解除绑定

unbindService(conn);

}

}

public class MusicService extends Service {

public MusicService() {

}

private MediaPlayer mPlayer;

@Override

public void onCreate() {

mPlayer=new MediaPlayer();   创建对象并加载数据

try {

mPlayer.setDataSource("/mnt/sdcard/Music/mu01.mp3");

mPlayer.prepare();

} catch (Exception e) {

e.printStackTrace();

}

}

@Override

public IBinder onBind(Intent intent) {

return new Player();   返回的绑定对象

}

 

class Player extends Binder implements IPlayer{

@Override

public void play() {

mPlayer.start();

}

@Override

public void pause() {

mPlayer.pause();

}

}

@Override

public void onDestroy() {

if(mPlayer!=null){

mPlayer.release();

mPlayer=null;

}

}

}

 

 

二、混合模式的service

 

混合模式service一般是绑定和启动相结合的一种service应用模式,此应用模式service的生命周期与启动和绑定的顺序相关。

 

1)混合模式其生命周期相关方法:

1)onCreate

2)onStartCommon (可以执行多次)

3)onBind

4)onUnbind

5)onDestory

例子2:混合模式其生命周期

public class MainActivity extends Activity implements OnClickListener {

 

Button startBtn,stopBtn,bindBtn,unBindBtn;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

    startBtn=(Button) findViewById(R.id.button1);

    bindBtn=(Button) findViewById(R.id.button2);

    unBindBtn=(Button) findViewById(R.id.button3);

    stopBtn=(Button) findViewById(R.id.button4);

    

    startBtn.setOnClickListener(this);

    bindBtn.setOnClickListener(this);

    unBindBtn.setOnClickListener(this);

    stopBtn.setOnClickListener(this);

}

private ServiceConnection conn=new ServiceConnection() {

@Override

public void onServiceDisconnected(ComponentName name) {

 

}

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

   Log.i("TAG", "onServiceConnected");

}

};

 

@Override

public void onClick(View v) {

if(v==startBtn){

 startService(new Intent(this,MyService01.class));

}else if(v==bindBtn){

 bindService(new Intent(this,MyService01.class),

 conn, Context.BIND_AUTO_CREATE);

}else if(v==unBindBtn){

 unbindService(conn);

}else if(v==stopBtn){

 stopService(new Intent(this,MyService01.class));

}

}

}

public class MyService01 extends Service {

public MyService01() {

}

 

@Override

public void onCreate() {

Log.i("TAG", "onCreate");

}

 

@Override

public IBinder onBind(Intent intent) {

Log.i("TAG", "onBind");

return new Binder();

}

 

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Log.i("TAG", "onStartCommand");

return super.onStartCommand(intent, flags, startId);

}

 

@Override

public boolean onUnbind(Intent intent) {

Log.i("TAG", "onUnbind");

return true;

}

 

@Override

public void onDestroy() {

Log.i("TAG", "onDestroy");

}

}

 

三、 Messenger对象的应用

1)概述

Messenger 对象可以实现跨进程之间的消息传递,它可以实现在serviceactivity之间的通讯,底层需要封装对应的一个handler对象。

2)相关方法

1)Messenger(binder) :绑定成功以后在connection中应用

2)Messenger(handler):replyTo

3)send(message):

例子3Messenger 对象可以实现跨进程之间的消息传递

public class MainActivity extends Activity {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

 

bindService(new Intent(this,MyService01.class),

conn, Context.BIND_AUTO_CREATE);(1)启动服务

}

 

private Handler aHandler=new Handler(){

public void handleMessage(Message msg) {

Log.i("TAG",String.valueOf(msg.obj));(9)处理service传过来的msg

};

};

private ServiceConnection conn=new ServiceConnection() {

@Override

public void onServiceDisconnected(ComponentName name) {

}

 

@Override

public void onServiceConnected(ComponentName name, IBinder binder) {

 

Messenger mGer=new Messenger(binder);(3)创建一个返回来binderMessenger

Message msg=Message.obtain();

msg.obj="hello service!";

msg.replyTo=new Messenger(aHandler);(4)创建绑定aHandlerMessenger赋值给message

try{

mGer.send(msg);//发送消息(5)

}catch(Exception e){}

}

};

protected void onDestroy() {

super.onDestroy();

unbindService(conn);

};

}

public class MyService01 extends Service {

public MyService01() {

}

private Handler bhandler=new Handler(){

public void handleMessage(Message msg) {(6)处理activity传过来的msg

 Log.i("TAG",String.valueOf(msg.obj));

 //可以回复消息给activity

 Message aMsg=Message.obtain();(7)创建一个msg

 aMsg.obj="hello activity";

 try{

 msg.replyTo.send(aMsg);(8)发送消息

 }catch(Exception e){e.printStackTrace();}

};

};

@Override

public IBinder onBind(Intent intent) {

Log.i("TAG", "onBind");

return new Messenger(bhandler).getBinder();(2)返回IBinder

}

}

 

例子4Messenger对象的应用:更新音乐列表

ublic class MainActivity extends ListActivity {

 

private SimpleCursorAdapter adapter;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

//setContentView(R.layout.activity_main);

    adapter=new SimpleCursorAdapter(this,

    android.R.layout.simple_list_item_2,

    null, new String[]{Media.TITLE,Media.ARTIST},

    new int[]{android.R.id.text1,android.R.id.text2},

    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    setListAdapter(adapter);

    startService(new Intent(this,MusicService.class));

    bindService(new Intent(this,MusicService.class),

        conn, Context.BIND_AUTO_CREATE);

}

private Handler aHandler=new Handler(){

public void handleMessage(Message msg) {

Cursor cursor=MusicService.getCursor();

adapter.changeCursor(cursor);

};

};

private ServiceConnection conn=new ServiceConnection() {

@Override

public void onServiceDisconnected(ComponentName name) {

}

@Override

public void onServiceConnected(ComponentName name, IBinder binder){

   //时机不合适

Message msg=Message.obtain();

msg.replyTo=new Messenger(aHandler);

try{

    new Messenger(binder).send(msg);

}catch(Exception e){}

}

};

protected void onListItemClick(android.widget.ListView l, View v, int position, long id) {

Intent intent=new Intent("ACTION_PLAY");

intent.putExtra("position", position);

startService(intent);

};

@Override

protected void onDestroy() {

super.onDestroy();

stopService(new Intent(this,MusicService.class));

}

public class MusicService extends Service {

public MusicService() {}

@Override

public void onCreate() {

new MusicAsyncTask().execute();

}

private Messenger replyTo;

private Handler sHandler=new Handler(){

public void handleMessage(Message msg) {

replyTo=msg.replyTo;

};

};

@Override

public IBinder onBind(Intent intent) {

  return new Messenger(sHandler).getBinder();

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

if(intent!=null){

String action=intent.getAction();

if("ACTION_PLAY".equals(action)){

 int pos=intent.getIntExtra("position",0);

 playMusic(pos);

}//else if()

}

return START_STICKY;

}

private MediaPlayer mPlayer;

public void playMusic(int pos){

if(mPlayer==null){

mPlayer=new MediaPlayer();

}

mPlayer.reset();

try{

cursor.moveToPosition(pos);

String path=cursor.getString(cursor.getColumnIndex(Media.DATA));

mPlayer.setDataSource(path);

mPlayer.prepare();

mPlayer.start();

}catch(Exception e){e.printStackTrace();};

}

class MusicAsyncTask extends AsyncTask<Void, Void, Cursor>{

@Override

protected Cursor doInBackground(Void... params) {

return getContentResolver()

.query(Media.EXTERNAL_CONTENT_URI,

null,Media.IS_MUSIC+"=1",

null,null);

}

@Override

protected void onPostExecute(Cursor cursor) {

//将数据如何更新到activity对应的页面上

    MusicService.cursor=cursor;

    //??????通知activity调用getCursor执行更新动作

    while(replyTo==null);

    try{

    replyTo.send(Message.obtain());

    }catch(Exception e){}

}

}

private static Cursor cursor;

/**什么时候调用此方法更新UI*/

public static Cursor getCursor() {

return cursor;

}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(day4.23总结_Service绑定和混合模式以及Messager的应用)