Service in Android (three)--remote service

Source: Internet
Author: User


1. Introduction:
(1) The role of Aidl

on the Android platform, each application is a separate JVM that runs in its own process space, and typically one process does not allow access to the memory space of another process (one app cannot access another). Interprocess communication is required when a user (program developer) wants to access the process space of another app in one app. In Android, remote services give us a way to implement interprocess communication, where aidl is a common way for application developers.

Aidl (Android Interface Definition Language) is an IDL language used to generate interprocess communication between two processes on Android devices (interprocess communication, IPC) The code. You can use Aidl to generate serializable parameters if you want to invoke the operation of another process (such as a service) object in one process (for example, activity). In other words, it is the activity of my app that calls for the service of other apps. Of course, the activity and service of the same app can also be used between different processes, which can be set up in the service configuration, Android :p rocess= ": Remote".


As you can see, the aidl scenario is that you can use Aidl to do this only if you allow clients to access your service from different applications for interprocess communication. For example, the Baidu map provides us with the following SERVICE:COM.BAIDU.LOCATION.F, we can use the service provided by declaring this service in the Manifest.xml file of our application. :
<service
Android:name= "COM.BAIDU.LOCATION.F"
Android:enabled= "true"
android:process= ": remote" >
</service>

2. The main example of this article:

The opening and application of remote services for application services, that is, the creation and use of Aidl:



Example Description:
(1). Function: Create remote service, calculate the number of files under the specified path in the service, and display them in the UI.
(2). You will learn: A. Definition and use of remote service;
B. Definition and use of aidl files.
To Create a process:
(1) Under the SRC of the project, a new text file is created, and the function to be implemented is placed in this file with the suffix. Aidl.
(2) After the project is refreshed, it will be found under Gen package, there is a Java file with the same name, which is automatically generated by the Aidl tool, inside, there is the function we want to implement.
(3) When the aidl is defined, we are going to implement our remote service. It is also inherited from the service.
(4) After the service is implemented, set it to remote in mainfest.xml. Note that the client server is in the same app, android:process= ": Remote", which is represented in the application, when the service is needed, A new process is created automatically. And if it is android:process= "remote", there is no ":" semicolon, then the global process is created, and the process is shared by different applications.
(5) Finally, to implement our client, the activity, to invoke the service.




3. Example code:
(1). aidl file: ifilecountservice.aidl:


Package com.example.remoteservicetest;
Interface ifilecountservice{
int getfilecnt (String path);
}






(2). Remote Service implementation: Myremoteservice.java:


Package com.example.remoteservicetest;

Import Java.io.File;


Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
Import android.os.RemoteException;
Import Android.util.Log;


public class Myremoteservice extends Service {
Static final String tag= "MyService";
private int filecnt = 0;

Define the inner class Myremoteserviceimpl, inherit our Aidl file automatically generated inner class,
and implement the interface method of our Aidl file definition
Private class Myremoteserviceimpl extends ifilecountservice.stub{


@Override
public int getfilecnt(String path) throws RemoteException {
LOG.E (TAG, "path");

File File = new file (path);
if (file.exists ()) {
if (File.isdirectory ()) {
File files[] = File.listfiles ();
if (files = = null) {
return 0;
}
for (int i = 0; i < files.length; i++) {
if (Files[i].isfile ()) {
filecnt++;
}
}


}


}
return filecnt;

}
}

@Override
Public IBinder Onbind (Intent arg0) {
Return to AIDL implementation
return new Myremoteserviceimpl ();
}


@Override
public void OnDestroy () {
LOG.E (TAG, "Release myservice");
Super.ondestroy ();
}


}



(3). Client Activity:AndroidRemoteActivity.java:


Package com.example.androidservicetest;


Import Com.example.remoteservicetest.IFileCountService;
Import Com.example.remoteservicetest.MyRemoteService;


Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
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 Androidremoteactivity extends Activity {
Static final String tag= "androidremoteactivity";

int filecnt = 0;

Private TextView TextView;
Button btn1;
Button btn2;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TextView = (TextView) Findviewbyid (R.id.textview);
BTN1 = (Button) Findviewbyid (R.id.button1);
BTN2 = (Button) Findviewbyid (R.id.button2);
Btn2.setvisibility (View.gone);
Btn1.settext ("Get File Count:");
if (btn1!=null)
Btn1.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Binding a service
filecnt = 0;
Bindservice ();
}
});
}

Ifilecountservice Iservice=null;
Private serviceconnection conn=new serviceconnection () {
@Override
public void onserviceconnected (componentname name, IBinder service) {
Returns the Aidl interface object, which can then be called by the Aidl method
Iservice=ifilecountservice.stub.asinterface (service);

try {
FILECNT=ISERVICE.GETFILECNT ("/sdcard");
}
catch (RemoteException e) {
LOG.E (TAG, "Error 000");
E.printstacktrace ();
}
LOG.E (TAG, "File Count:" +filecnt);
Textview.settext ("File count:" +filecnt);
}
@Override
public void onservicedisconnected (componentname name) {
LOG.I (TAG, "onservicedisconnected");
}
};

private void Bindservice () {
Intent intent=new Intent (this,myremoteservice.class);
StartService (Intent);
Bindservice (Intent, Conn, context.bind_auto_create);
}
}


(4). Androidmanifest.xml:


<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Com.example.androidservicetest"
Android:versioncode= "1"
Android:versionname= "1.0" >


<uses-sdk
Android:minsdkversion= "8"
Android:targetsdkversion= "/>"


<application
Android:allowbackup= "true"
android:icon= "@drawable/ic_launcher"
Android:label= "@string/app_name"
Android:theme= "@style/apptheme" >
<activity
Android:name= "Com.example.androidservicetest.MainActivity"
Android:label= "@string/app_name" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>


<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

<activity
Android:name= "Com.example.androidservicetest.AndroidLocalServiceActivity" >

</activity>

<activity
Android:name= "Com.example.androidservicetest.AndroidRemoteActivity" >

</activity>


<service android:name= "Com.example.androidservicetest.PackageFindService" >
<intent-filter>
<action android:name= "Com.test.service"/>
</intent-filter>
</service>

<service android:name= "Com.example.remoteservicetest.MyRemoteService"
android:process= ": Remote"
>
<intent-filter>
<action android:name= "Com.example.remoteservicetest.IFileCountService"/>
</intent-filter>
</service>
</application>


</manifest>




4. Test results:
After running the program, two buttons are displayed, the first one is the test Locel service, the second one is the test remote service, the second point, and then the number of files in the SDcard root directory will be displayed on the screen.


5. Code Download:


http://download.csdn.net/detail/liranke/8401933





Service in Android (three)--remote service

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.