Big Fairy says Android studio implements service Aidl

Source: Internet
Author: User

Today in the development process to use the AIDL call, prior to the eclipse has a lot of tutorials, easy to use, now just replaced Android Studio, it is undeniable that studio is really powerful, but a lot of features still need to explore.

Aidl (Android Interface definition Language) is the meaning of the Android Interface Definition language, which can be used to communicate across processes between a service and multiple application components. This enables multiple applications to share the same service functionality.

To get to the point, today's topic is the remote Service Setup aidl for communication, and a small demo to showcase Aidl's implementation in Android studio:

1. Build a simple service framework that includes only startservice (intent), and the framework is shown in the following code

2. Then establish the Aidl, by clicking on the build Aidl file,

After Setup, the Aidl file appears.

But at this time there is no aidl Java file generation, in fact, Android Studio is also with automatic generation, just need to confirm some information before it can be generated. At this point, we can find that there are no files under the directory Build-->generated-->source-->aidl-->test-->debug

At this point, open the Androidmanifest.xml and confirm the package value, as I

A critical step to confirm that the package name of the Aidl file is the same as that of the androidmainifest.xml. If consistent, click Build-->make Project to generate the appropriate Java file. If not, change the package name to Aidl, and then click Generate to create the effect.

At this point, you can call the remote service through AIDL in the program, implement AIDL and remote service to communicate, the code is shown below.

Mainactivity.java

 Public classMainactivityextendsactionbaractivity {PrivateMyserviceaidl Myserviceaidl; PrivateIntent binderintent; Private Final Static Booleancreate_flag=true; Private Final Static Booleandestory_flag=false; Private Final StaticString tag= "Mainactivity"; PrivateServiceconnection sc =Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {Myserviceaidl=MyServiceAIDL.Stub.asInterface (service); Try {                //Remote Call via AidlLOG.D (TAG, "++start download++");            Myserviceaidl.download (); } Catch(RemoteException e) {e.printstacktrace (); }} @Override Public voidonservicedisconnected (componentname name) {}}; @Overrideprotected voidonCreate (Bundle savedinstancestate) {log.d (TAG,"++mainactivity oncreate++"); Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //Open ServiceIntent Intent =NewIntent ( This, Mainservice.class);        StartService (Intent); //connecting remote service and activityBinderintent =NewIntent ( This, Mainservice.class); Bundle Bundle=NewBundle (); Bundle.putboolean ("Flag", Create_flag);        Binderintent.putextras (bundle);    Bindservice (Binderintent, SC, bind_auto_create); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); LOG.D (TAG,"++mainactivity ondestroy++"); BooleanFlag =false; //Pause ServiceIntent Intent =NewIntent ( This, Mainservice.class);        StopService (Intent); //disconnecting from a remote serviceUnbindservice (SC); }}

Mainservice.java

 Public classMainserviceextendsService {BooleanFlag; Private Final StaticString TAG = "Mainservice"; @Override Public voidOnDestroy () {Super. OnDestroy (); LOG.D (TAG,"++mainservice ondestroy++"); Flag=false; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {        return Super. Onstartcommand (Intent, flags, Startid); } @Override Public voidonCreate () {Super. OnCreate (); LOG.D (TAG,"++mainservice oncreate++"); Notification No=NewNotification (R.drawable.ic_launcher, "notice arrives", System.currenttimemillis ()); Intent Intent=NewIntent ( This, Mainactivity.class); Pendingintent Pi= Pendingintent.getactivity ( This, 0, intent, 0); No.setlatesteventinfo ( This, "Aidldemo", "Running", PI); Startforeground (1, no); } @Override Publicibinder onbind (Intent Intent) {Bundle bundle=Intent.getextras (); Flag= Bundle.getboolean ("Flag");        SYSTEM.OUT.PRINTLN (flag); returnMS; } myserviceaidl.stub Ms=Newmyserviceaidl.stub () {@Override Public voidDownLoad ()throwsRemoteException {NewThread (NewRunnable () {inti = 0; @Override Public voidrun () {//if the thread condition is not reached, it will continue to run in the background even if the service is closed                     while(flag) {Try{i++; System.out.println (The value of "I" is "+i); Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("Exit Service");        }}). Start (); }    };}

Androidmanifest.xml

<ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme">        <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name">            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>        <ServiceAndroid:name=". Mainservice "android:process= ": Remote"></Service>    </Application>

Myserviceaidl.aidl

// Myserviceaidl.aidl  Package Com.example.wanghao.aidldemo; // Declare any non-default types here with import statements Interface myserviceaidl {     void  DownLoad ();}

Reference article: http://blog.csdn.net/guolin_blog/article/details/9797169

Android development enthusiasts, if there are errors in the text, look at the message of the great God, learn from each other, common progress!

Big Fairy says Android studio implements service Aidl

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.