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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android帶進度條的文件上傳示例(使用AsyncTask異步任務(wù))
這篇文章主要介紹了Android帶進度條的文件上傳示例(使用AsyncTask異步任務(wù)),使用起來比較方便,將幾個方法實現(xiàn)就行,感興趣的小伙伴們可以參考一下。2016-11-11在Android環(huán)境下WebView中攔截所有請求并替換URL示例詳解
這篇文章主要介紹了在Android環(huán)境下WebView中攔截所有請求并替換URL示例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Android用代碼獲取手機root之后的最高權(quán)限
機得root之后通過代碼可以獲得最高權(quán)限如果沒有root的話請不要往下看,毫無意義,root之后的朋友可以參考下本文或許有意想不到的收獲2013-03-03詳解AndroidStudio中代碼重構(gòu)菜單Refactor功能
這篇文章主要介紹了AndroidStudio中代碼重構(gòu)菜單Refactor功能詳解,本文通過代碼演示,功能截圖來詳細(xì)說明as為大名重構(gòu)提供的各項功能,需要的朋友可以參考下2019-11-11Android實現(xiàn)長按圓環(huán)動畫View效果的思路代碼
這篇文章主要介紹了Android實現(xiàn)長按圓環(huán)動畫View效果,本文給大家分享實現(xiàn)思路,通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09Android 自定義加載動畫Dialog彈窗效果的示例代碼
這篇文章主要介紹了Android 自定義加載動畫Dialog彈窗效果,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06Android自定義控件ViewFipper實現(xiàn)豎直跑馬燈效果
這篇文章主要為大家詳細(xì)介紹了Android自定義控件ViewFipper實現(xiàn)豎直跑馬燈效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12