标签:
1.作用:Binder是客户端与服务器端的通信的媒介(连接各种Manager的桥梁),客户端通过Binder对象获取服务器端提供的数据
(为什么要用Binder来提供数据呢,服务器不能自己传给客户端数据么?)
因为服务器端通过Binder创建接口暴露自身数据,能够防止其他黑客入侵,导致数据被偷走或者篡改,只能让其他用户获取我们想要给他们的数据,不让他们从服务器自己拿数据。
步骤一:创建Book.java类、Book.aidl类、IBookManager.aidl类
步骤二:创建Service并重写IBookManager类
/*BookService类*/ public class BookService extends Service { private static final String TAG = "BookService"; private List<Book> mBookList; //如何创建在AIDL创建的IBookManager类 @Nullable private Binder mIBookManager = new IBookManager.Stub(){ @Override public List<Book> getBooksItem() throws RemoteException { return mBookList; } @Override public void addBook(Book book) throws RemoteException { Log.d(TAG,"新书加入"+book.toString()); } }; @Override public void onCreate() { super.onCreate(); mBookList = new ArrayList<>(); mBookList.add(new Book(1,"疯狂Android讲义")); mBookList.add(new Book(2,"Android开发艺术探索")); } @Override public IBinder onBind(Intent intent) { return mIBookManager; } }
不要忘了在AndroidManifest.xml中注册
<service android:name=".BookService" android:process=":Remote"> <!--Service创建新的进程--> </service>
步骤三:在客户端中启动Service
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private IBookManager mService; private List<Book> mBookList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //必须创建ServiceConnection对象,详见Service类的使用 ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { //将服务器的Binder转换陈客户端的Binder mService = IBookManager.Stub.asInterface(service); try { //获取所有书籍 mBookList = mService.getBooksItem(); Log.d(TAG,mBookList.get(0).toString()); //加入书籍 mService.addBook(new Book(2,"IOS")); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } }; //启动Service Intent intent = new Intent(this,BookService.class); bindService(intent,connection,BIND_AUTO_CREATE); } }
未理解的问题:当application结束时候,Service的进程是否也会终止? 与线程的Binder的区别
标签:
原文地址:http://www.cnblogs.com/rookiechen/p/5352134.html