Android IPC機制ACtivity綁定Service通信代碼實例
Binder通信過程類似于TCP/IP服務(wù)連接過程binder四大架構(gòu)Server(服務(wù)器),Client(客戶端),ServiceManager(DNS)以及Binder驅(qū)動(路由器)
其中Server,Client,ServiceManager運行于用戶空間,驅(qū)動運行于內(nèi)核空間。這四個角色的關(guān)系和互聯(lián)網(wǎng)類似:Server是服務(wù)器,Client是客戶終端,SMgr是域名服務(wù)器(DNS),驅(qū)動是路由器。
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(); }}
上面是一個 實現(xiàn)了parcelable的實體類,就是將book序列化,在putExtra到Service時會被寫入內(nèi)存加快程序速度
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;// 啟動服務(wù)按鈕 Button shutDownServiceButton;// 關(guān)閉服務(wù)按鈕 Button startBindServiceButton;// 啟動綁定服務(wù)按鈕 @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); } /** 啟動服務(wù)的事件監(jiān)聽 */ public Button.OnClickListener startService = new Button.OnClickListener() { public void onClick(View view) { /** 單擊按鈕時啟動服務(wù) */ Intent intent = new Intent(MainActivity.this, CountService.class); startService(intent); Log.v('MainStadyServics', 'start Service'); } }; /** 關(guān)閉服務(wù) */ public Button.OnClickListener shutdownService = new Button.OnClickListener() { public void onClick(View view) { /** 單擊按鈕時啟動服務(wù) */ Intent intent = new Intent(MainActivity.this, CountService.class); /** 退出Activity是,停止服務(wù) */ stopService(intent); Log.v('MainStadyServics', 'shutDown serveice'); } }; /** 打開綁定服務(wù)的Activity */ public Button.OnClickListener startBinderService = new Button.OnClickListener() { public void onClick(View view) { /** 單擊按鈕時啟動服務(wù) */ Intent intent = new Intent(MainActivity.this, UseBrider.class); startActivity(intent); Log.v('MainStadyServics', 'start Binder Service'); } };}
mainActivity中當(dāng)使用startService()啟動Service時會調(diào)用Service的onStartCommand()
當(dāng)使用bindService()則會調(diào)用onBind()方法,可能會覺了看的又看怎么沒看到bindService()這個方法呢
重點在
Intent intent = new Intent(MainActivity.this, UseBrider.class);startActivity(intent);
繼續(xù)上代碼
UseBrider.java
/** 通過bindService和unBindSerivce的方式啟動和結(jié)束服務(wù) */public class UseBrider extends FragmentActivity { /** 參數(shù)設(shè)置 */ 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開始服務(wù) * conn */ bindService(intent, conn, Context.BIND_AUTO_CREATE); } private ServiceConnection conn = new ServiceConnection() { /* * 這個方法會獲取到CountService的onBind方法中返回的Binder對象 * 然后就可以對服務(wù)進行某種操作了 */ public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub countService = ((CountService.ServiceBinder) service).getService(); countService.callBack(); } /** 無法獲取到服務(wù)對象時的操作 */ 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{ /**創(chuàng)建參數(shù)*/ 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('使用綁定服務(wù)', 10, 30, textPaint); textPaint.setColor(Color.GREEN); textPaint.setTextSize(18); canvas.drawText('使用綁定服務(wù)后,這個Activity關(guān)閉后', 20, 60, textPaint); canvas.drawText('綁定的服務(wù)也會關(guān)閉', 5, 80, textPaint); } }
UseBriderFace.java類其實就是用java定義的布局可以用xml文件代替
countService.java
package com.example.android_binder_testservice;/**引入包*/import android.app.Service;// 服務(wù)的類import android.os.IBinder;import android.os.Parcel;import android.os.RemoteException;import android.os.Binder;import android.content.Intent;import android.util.Log;/** 計數(shù)的服務(wù) */public class CountService extends Service { private String TAG = CountService.class.getSimpleName(); /** 創(chuàng)建參數(shù) */ boolean threadDisable; int count; Book book;/* * 當(dāng)通過bindService()啟動CountService時會調(diào)用這個方法并返回一個ServiceBinder對象 * 這個Binder對象封裝著一個CountService實例, * 客戶端就可以通過ServiceBinder對服務(wù)端進行一些操作 */ 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(); /** 創(chuàng)建一個線程,每秒計數(shù)器加一,并在控制臺進行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(); /** 服務(wù)停止時,終止計數(shù)進程 */ 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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于javascript處理二進制圖片流過程詳解2. 解決android studio引用遠(yuǎn)程倉庫下載慢(JCenter下載慢)3. Gitlab CI-CD自動化部署SpringBoot項目的方法步驟4. ajax請求添加自定義header參數(shù)代碼5. ASP基礎(chǔ)知識VBScript基本元素講解6. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)7. Kotlin + Flow 實現(xiàn)Android 應(yīng)用初始化任務(wù)啟動庫8. idea刪除項目的操作方法9. 教你如何寫出可維護的JS代碼10. 使用python 計算百分位數(shù)實現(xiàn)數(shù)據(jù)分箱代碼
