今天開發(fā)了一個功能,通過Android的AIDL機制完成兩個app間的通信。功能需求很簡單,一個客戶端app,叫做client,一個服務端app叫orderManager;客戶端負責展示訂單列表,并且可以向服務端添加訂單;服務端負責管理訂單,可以對外提供訂單信息。
創(chuàng)新互聯建站自2013年創(chuàng)立以來,先為長安等服務建站,長安等地企業(yè),進行企業(yè)商務咨詢服務。為長安企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
閑言少敘,下面直接上代碼。
1、編寫bean類。
首先在client中定義OrderBean類,字段很簡單,注意需要實現Parcelable接口:
package com.example.wang.client.bean; import android.os.Parcel; import android.os.Parcelable; public class OrderBean implements Parcelable{ private String id; private String name; private int amount; public OrderBean(){} public OrderBean(String id, String name, int amount) { this.id = id; this.name = name; this.amount = amount; } protected OrderBean(Parcel in) { id = in.readString(); name = in.readString(); amount = in.readInt(); } public static final CreatorCREATOR = new Creator () { @Override public OrderBean createFromParcel(Parcel in) { return new OrderBean(in); } @Override public OrderBean[] newArray(int size) { return new OrderBean[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(id); dest.writeString(name); dest.writeInt(amount); } //get/set方法略 }
2、定義aidl文件。aidl文件的存放位置在Android Studio中一般存放在如下路徑:
client/src/aidl/…
// OrderBean.aidl package com.example.wang.client.bean;//存放的包路徑同bean類 parcelable OrderBean;//通信用到的Parcelable需要聲明,并且使用小寫的parcelable // IBookManager.aidl package com.example.wang.client.aidl; import com.example.wang.client.bean.OrderBean;//除了系統提供的對象,都需要明確導入 interface IOrderManager { ListgetAll(); void add(in OrderBean bean); }
3、定義布局文件,編寫MainActivity。這個很簡單,Button和RecyclerView結合即可:
#activity_main.xml - 主頁面布局 <?xml version="1.0" encoding="utf-8"?>
還要寫一個item_order.xml,用于RecyclerView的展示,很簡單,此處略過。
//MainActivity.java package com.example.wang.client; ... public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private ListorderList; private IOrderManager orderManager; //UI private Button search_button; private Button add_button; private RecyclerView recyclerView; private OrderAdapter adapter; ServiceConnection conn = new ServiceConnection() {//這個最重要,用于連接Service @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("MainActivity.conn","@@ onServiceConnected name="+name); IOrderManager manager = IOrderManager.Stub.asInterface(service); orderManager = manager; refreshOrderList(); try { service.linkToDeath(deathRecipient, 0); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i("MainActivity.conn","@@ onServiceDisconnected name="+name); } }; IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() {//注冊一個死亡代理,監(jiān)測連接狀態(tài) @Override public void binderDied() { Log.i("MainActivity","@@ binderDied "+(orderManager==null)); if(orderManager==null){ return; } orderManager.asBinder().unlinkToDeath(deathRecipient, 0); orderManager = null; //重新綁定 bindOrderService(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("MainActivity","@@ onCreate"); setContentView(R.layout.activity_main); getLayoutInflater(); //view search_button=findViewById(R.id.search_button); add_button=findViewById(R.id.add_button); recyclerView=findViewById(R.id.recyclerView); //組裝recyclerView LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); adapter=new OrderAdapter(this); recyclerView.setAdapter(adapter); //onclick search_button.setOnClickListener(this); add_button.setOnClickListener(this); //bind bindOrderService(); } private void bindOrderService(){ Intent intent = new Intent("com.example.wang.ordermanager.OrderService"); intent.setPackage("com.example.wang.ordermanager"); intent.addCategory(Intent.CATEGORY_LAUNCHER); bindService(intent, conn, Context.BIND_AUTO_CREATE); } /** * 重新獲取數據并刷新列表。 */ private void refreshOrderList(){ try { if(orderManager!=null){ orderList = orderManager.getAll(); } if(orderList!=null){ adapter.setData(orderList); adapter.notifyDataSetChanged(); } } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onClick(View v) { if(v==search_button){ //刷新訂單 refreshOrderList(); }else if(v==add_button){ //增加訂單 try { OrderBean orderBean=new OrderBean(); Random random=new Random(); orderBean.setAmount(random.nextInt(800)+100); orderBean.setId(random.nextInt(100000000)+100000+""); orderBean.setName("玩具"+random.nextInt()); orderManager.add(orderBean); refreshOrderList(); } catch (RemoteException e) { e.printStackTrace(); } } } @Override protected void onDestroy() { super.onDestroy(); unbindService(conn); } }
4、編寫服務端代碼
這里主要做兩件事,第一個是移植aidl文件和bean類,將client中的aidl文件和OrderBean移植過來,文件路徑要保持一致,第二個是編寫OrderService.java類。
//OrderService.java package com.example.wang.ordermanager; ... public class OrderService extends Service{ private CopyOnWriteArrayListlist = new CopyOnWriteArrayList<>(); @Override public void onCreate() { super.onCreate(); Log.i("OrderService","@@ onCreate"); } @Nullable @Override public IBinder onBind(Intent intent) { Log.i("OrderService","@@ onBind"); return binder; } Binder binder = new IOrderManager.Stub(){ @Override public List getAll() throws RemoteException { return list; } @Override public void add(OrderBean bean) throws RemoteException { list.add(bean); } }; }
OrderService服務在AndroidManifest.xml中的配置如下:
代碼編寫就完成了,運行時需要先運行服務端app,再運行client,如果運行過程中OrderService服務斷掉了,client會通過死亡代理得到通知,再重新綁定即可。
運行如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯。