您好,登錄后才能下訂單哦!
本篇文章為大家展示了Android IPC機制ACtivity綁定Service實現通信,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
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; } } }
上述內容就是Android IPC機制ACtivity綁定Service實現通信,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。