Binder通信过程类似于TCP/IP服务连接过程binder四大架构Server(服务器),Client(客户端),ServiceManager(DNS)以及Binder驱动(路由器)
其中Server,Client,ServiceManager运行于用户空间,驱动运行于内核空间。这四个角色的关系和互联网类似:Server是服务器,Client是客户终端,SMgr是域名服务器(DNS),驱动是路由器。
book.java
package com.example.android_binder_testservice; import android.os.Parcel; import android.os.Parcelable; public class Book implements Parcelable { private String bookName; private String author; private int publishDate; public Book() { } public Book(String bookName, String author, int publishDate) { super(); this.bookName = bookName; this.author = author; this.publishDate = publishDate; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPublishDate() { return publishDate; } public void setPublishDate(int publishDate) { this.publishDate = publishDate; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeString(bookName); out.writeString(author); out.writeInt(publishDate); } public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { @Override public Book[] newArray(int size) { return new Book[size]; } @Override public Book createFromParcel(android.os.Parcel source) { return new Book(source); } }; public Book(Parcel in) { bookName = in.readString(); author = in.readString(); publishDate = in.readInt(); } }
上面是一个 实现了parcelable的实体类,就是将book序列化,在putExtra到Service时会被写入内存加快程序速度
mainActivity.java
package com.example.android_binder_testservice; import android.os.Bundle; import android.util.Log; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { Button startServiceButton;// 启动服务按钮 Button shutDownServiceButton;// 关闭服务按钮 Button startBindServiceButton;// 启动绑定服务按钮 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWidget(); regiestListener(); } public void getWidget(){ startServiceButton = (Button) findViewById(R.id.startService); startBindServiceButton = (Button) findViewById(R.id.bindService); shutDownServiceButton = (Button) findViewById(R.id.stopService); } public void regiestListener() { startServiceButton.setOnClickListener(startService); shutDownServiceButton.setOnClickListener(shutdownService); startBindServiceButton.setOnClickListener(startBinderService); } /** 启动服务的事件监听 */ public Button.OnClickListener startService = new Button.OnClickListener() { public void onClick(View view) { /** 单击按钮时启动服务 */ Intent intent = new Intent(MainActivity.this, CountService.class); startService(intent); Log.v("MainStadyServics", "start Service"); } }; /** 关闭服务 */ public Button.OnClickListener shutdownService = new Button.OnClickListener() { public void onClick(View view) { /** 单击按钮时启动服务 */ Intent intent = new Intent(MainActivity.this, CountService.class); /** 退出Activity是,停止服务 */ stopService(intent); Log.v("MainStadyServics", "shutDown serveice"); } }; /** 打开绑定服务的Activity */ public Button.OnClickListener startBinderService = new Button.OnClickListener() { public void onClick(View view) { /** 单击按钮时启动服务 */ Intent intent = new Intent(MainActivity.this, UseBrider.class); startActivity(intent); Log.v("MainStadyServics", "start Binder Service"); } }; }
mainActivity中当使用startService()启动Service时会调用Service的onStartCommand()
当使用bindService()则会调用onBind()方法,可能会觉了看的又看怎么没看到bindService()这个方法呢
重点在
Intent intent = new Intent(MainActivity.this, UseBrider.class);
startActivity(intent);
继续上代码
UseBrider.java
/** 通过bindService和unBindSerivce的方式启动和结束服务 */ public class UseBrider extends FragmentActivity { /** 参数设置 */ CountService countService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new UseBriderFace(this)); Intent intent = new Intent(UseBrider.this, CountService.class); intent.putExtra("book", new Book("name", "an", 1999)); /** 进入Activity开始服务 * conn */ bindService(intent, conn, Context.BIND_AUTO_CREATE); } private ServiceConnection conn = new ServiceConnection() { /* * 这个方法会获取到CountService的onBind方法中返回的Binder对象 * 然后就可以对服务进行某种操作了 */ public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub countService = ((CountService.ServiceBinder) service).getService(); countService.callBack(); } /** 无法获取到服务对象时的操作 */ public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub countService = null; } }; protected void onDestroy() { super.onDestroy(); this.unbindService(conn); Log.v("MainStadyServics", "out"); } }
UseBriderFace.java
public class UseBriderFace extends View{ /**创建参数*/ public UseBriderFace(Context context){ super(context); } public void onDraw(Canvas canvas){ canvas.drawColor(Color.WHITE);//画白色背景 /**绘制文字*/ Paint textPaint = new Paint(); textPaint.setColor(Color.RED); textPaint.setTextSize(30); canvas.drawText("使用绑定服务", 10, 30, textPaint); textPaint.setColor(Color.GREEN); textPaint.setTextSize(18); canvas.drawText("使用绑定服务后,这个Activity关闭后", 20, 60, textPaint); canvas.drawText("绑定的服务也会关闭", 5, 80, textPaint); } }
UseBriderFace.java类其实就是用java定义的布局可以用xml文件代替
countService.java
package com.example.android_binder_testservice; /**引入包*/ import android.app.Service;// 服务的类 import android.os.IBinder; import android.os.Parcel; import android.os.RemoteException; import android.os.Binder; import android.content.Intent; import android.util.Log; /** 计数的服务 */ public class CountService extends Service { private String TAG = CountService.class.getSimpleName(); /** 创建参数 */ boolean threadDisable; int count; Book book; /* * 当通过bindService()启动CountService时会调用这个方法并返回一个ServiceBinder对象 * 这个Binder对象封装着一个CountService实例, * 客户端就可以通过ServiceBinder对服务端进行一些操作 */ public IBinder onBind(Intent intent) { Log.i(TAG, "onBind"); book = intent.getParcelableExtra("book"); return new ServiceBinder(); } @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 super.onUnbind(intent); } @Override public void onRebind(Intent intent) { Log.i(TAG, "onRebind"); super.onRebind(intent); } public void onCreate() { super.onCreate(); /** 创建一个线程,每秒计数器加一,并在控制台进行Log输出 */ new Thread(new Runnable() { public void run() { while (!threadDisable) { try { Thread.sleep(1000); } catch (InterruptedException e) { } count++; Log.v("CountService", "Count is" + count); } } }).start(); Log.i(TAG, "onCreate"); } public void onDestroy() { super.onDestroy(); /** 服务停止时,终止计数进程 */ this.threadDisable = true; Log.i(TAG, "onDestroy"); } public int getConunt() { return count; } public void callBack(){ Log.i(TAG, "hello,i am a method of CountService"); } class ServiceBinder extends Binder { public CountService getService() { return CountService.this; } } }
代码解释有了,想不出来了
源码下载地址:http://git.oschina.net/zwh_9527/Binder
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/196716/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)