Remote binding of Android learning to call service

Source: Internet
Author: User

[Java] [java] recently I have been studying service controls. The front-end service and the service bound to the local control are easy to understand, and I have hardly encountered any problems, however, when remotely calling the service, the system imitates the example in the book and finds that the desired result is not obtained. If we get the source code of the example in the book, there will still be problems, so after a few days of self exploration and online reference some of the information, the main help from the http://www.cnblogs.com/TerryBlog/archive/2010/08/24/1807605.html http://ericchan2012.iteye.com/blog/1554197 these 2 URLs. Next, go to the topic to learn the results of remotely binding and calling services over the past few days. Remote binding and calling of service is mainly used for sharing information of different processes. For example, on the server and client, set a service to provide methods or information, and then the client can directly call the Server service to provide methods or information. The premise is that the client must have the same AIDL as the server, and then the server has registered the AIDL on the system used by the client (that is, once installed and run ), then the client can remotely bind and call the service on the server. The specific steps are as follows: 1. first, it is Server 1) Create an android Application Project 2) create an AIDL file in the bag where the main Aitivity is located, this is an ADT that will automatically generate a JAVA file with the same name as the AIDL file in the gen directory (here, AidlService. java is generated in the next step. You can ignore it here.) 3) create a class (AidlService) used to use the service, as shown in. java) the code for each file is as follows: AidlServerActivity. java [java] package com. ds. server; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListene R; import android. widget. button; import android. widget. toast; public class AidlServerActivity extends Activity {/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); Button bt = (Button) findViewById (R. id. bt); bt. setOnClickListener (new OnClickListener () {@ Override public voi D onClick (View v) {// TODO Auto-generated method stub Intent service = new Intent (AidlServerActivity. this, AidlService. class); startService (service); Toast. makeText (AidlServerActivity. this, "service started", Toast. LENGTH_LONG ). show () ;}}) ;}} IAidlService. aidl [java] package com. ds. server; interface IAidlService {int getType ();} AidlService. java [java] package com. ds. server; import android. app. Service; import android. content. intent; import android. OS. IBinder; import android. OS. remoteException; import android. util. log; public class AidlService extends Service {private boolean unrunnable; private int count; private class MyBinder extends IAidlService. stub {@ Override public int getType () throws RemoteException {// TODO Auto-generated method stub return 100;} private void Log (String Str) {Log. d ("AidlService", "------" + str + "------") ;}@ Override public void onCreate () {super. onCreate ();/* new Thread (new Runnable () {@ Override public void run () {while (! Unrunnable) {try {Thread. sleep (1000);} catch (InterruptedException e) {} count ++; Log. v ("AidlService", "count:" + count );}}}). start (); */Log. v ("RemoteCountService", "onCreate"); Log ("service create");}/* @ Override public void onStart (Intent intent, int startId) {Log ("service start id =" + startId);} */@ Override public IBinder onBind (Intent t) {Log ("service on bind "); return new MyBinder () ;}@ O Verride public void onDestroy () {Log ("service on destroy"); unrunnable = true; super. onDestroy ();}/* @ Override public boolean onUnbind (Intent intent) {Log ("service on unbind"); return super. onUnbind (intent);} public void onRebind (Intent intent) {Log ("service on rebind"); super. onRebind (intent);} */} layout file AndroidManifest. xml [html] <? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. ds. server "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 8 "/> <application android: icon = "@ drawable/ic_launcher" android: label = "@ string/app_name"> <activity android: name = ". aidlServerActivity "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. inten T. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> <service android: name = ". aidlService "android: enabled =" true "android: process =": remote "> <intent-filter> <! -- Complete path name of AIDL. It must be specified that the client can find its implementation class through the AIDL class name --> <action android: name = "com. ds. server. IAidlService "/> <category android: name =" android. intent. category. DEFAULT "/> </intent-filter> </service> </application> </manifest> here, the work on the server is done, and the work on the client is followed. 2. next, the client: 1) First, create a project 2) then, copy some files on the server (create com. ds. server, and then copy the file (IAidlService. java) The following is the file content AidlClientActivity. java [java] package com. ds. client; import com. ds. server. IAidlService; import android. app. activity; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; import android. OS. bundle; import android. OS. IBinder; import Android. OS. remoteException; import android. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class AidlClientActivity extends Activity {IAidlService iservice; int count; private ServiceConnection connection = new ServiceConnection () {public void onServiceConnected (ComponentName, IBinder service) {// TODO Auto-generated method stub // zookeeper ervice IDL zookeeper � iservice = IAidlService. stub. asInterface (service); Log. I ("Client", "Bind Success:" + iservice);} public void onServiceDisconnected (ComponentName name) {// TODO Auto-generated method stub iservice = null; Log. I ("Client", "onServiceDisconnected") ;}};/** Called when the activity is first created. * // @ Override public void onCreate (B Undle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); final TextView TV = (TextView) findViewById (R. id. TV); Button bt = (Button) findViewById (R. id. bt); bt. setOnClickListener (new OnClickListener () {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub Intent service = new Intent (IAidlService. class. getName (); bindService (service, con Nection, BIND_AUTO_CREATE); if (iservice! = Null) {try {Log. v ("AidlClientActivity", "oncreate" + iservice. getType () + "" + count);} catch (RemoteException e) {e. printStackTrace () ;}} else {count ++ ;}}) ;}} AndroidManifest. xml [html] <? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. ds. client "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 8 "/> <application android: icon = "@ drawable/ic_launcher" android: label = "@ string/app_name"> <activity android: name = ". aidlClientActivity "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. inten T. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> </application> </manifest>. In this way, the client is finished, but here I want to talk about the next question. You may see that there is a count variable in the Activity file of the client, which is redundant, but this is to illustrate the need for this problem. The initial count is 0. After I run the client, click the bind button on the left and the LogCat verbose window will show why the Log is not executed. v ("AidlClientActivity", "oncreate" + iservice. getType () + "" + count); then I click bind to display the expected result. Here you will find that the count is changed to 1, that is, once count + 1 is executed, it indicates that for the first time, only the binding is performed, the returned iservice is null, and the object will be returned more than the second time. This is where I have been wrong. I understood it wrong. The program I wrote earlier has no buttons. It is bound to call the service after the client is started directly, if you do not have a button, you cannot press it multiple times. Here, I finally understand some of its operational mechanisms. I will write it here first, and what new discoveries will be updated in a timely manner.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.