📜 ⬆️ ⬇️

The interaction between the application and the service

Introduction


In this publication I want to show an example of the interaction (receiving and sending data) of an application and service in the Android operating system. The publication is designed for novice programmers, there will be practically no theory, since the main goal is to tell how to do it.


The interaction scheme will be the following, the application registers the receiver of broadcast messages , which receives data from the service, then the service itself is started, data transfer from application to service will be implemented through the AIDL mechanism.

Before you begin, you need to have the basic components for creating Android applications, such as Java (JDK and JRE), Eclipse, Android SDK and ADT plugin for Eclipse, you can read about how to install and configure it on the pages of Habrahabr .
')

1. Create an application and service


Launch Eclipse, then press Ctrl + N, in the dialog box that appears, select the item “Android Project” and follow the instructions shown in the image:



Thus, we have created an application framework, now we need to add a service, for this we need to create a new class inherited from the Service class, right-click on the package of our project:



Next, a dialog box appears in which you must do the following:



Now we add our service to the AndroidManifest.xml file, for this we open it in Eclipse and do the following:



2. Getting information from the service


To receive information from the service, you need to register the receiver of broadcast messages. To do this, add the appropriate code to the onCreate and onDestroy methods of the application:

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //  IntentFilter filter = new IntentFilter(); filter.addAction("AppService"); service = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("AppService")) { Log.i("AppService",intent.getStringExtra("Data")); } } }; registerReceiver(service, filter); //  startService(new Intent(this,MainService.class)); } @Override protected void onDestroy() { super.onDestroy(); if(service!= null){unregisterReceiver(service);} stopService(new Intent(this,MainService.class)); } 


In the service, the information is transmitted by sending a broadcast message, add the onCreate method and send:

 @Override public void onCreate() { super.onCreate(); Intent in = new Intent("AppService"); in.putExtra("Data"," ."); sendBroadcast(in); } 


We start our application and see in LogCat the information received from the service and processed in the main application code:



3. Data transfer to service


Now we add the AIDL mechanism to our project, for this we add a file with the aidl extension:



A dialog box appears in which you enter the following data:



A window for editing the UpdateService.aidl file will open, add the following code:

 package ru.blagin.appservice; interface UpdateService { String UpdateSrv(String strTest); } 


After that, you need to save the changes and rebuild the project, if the automatic build option is disabled, then the ADT plug-in will automatically generate the code necessary for the operation of this mechanism. Now you need to change the code of the main application and service. Add the implementation of the ServiceConnection interface to the main application code, change the start and stop of the service, and also add a button that, when clicked, transfers data:

 package ru.blagin.appservice; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; 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 ru.blagin.appservice.UpdateService; public class Main extends Activity { private BroadcastReceiver brService = null; UpdateService iService = null; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { iService = null; } public void onServiceConnected(ComponentName name, IBinder service) { iService = UpdateService.Stub.asInterface(service); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //  IntentFilter filter = new IntentFilter(); filter.addAction("AppService"); brService = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("AppService")) { Log.i("AppService",intent.getStringExtra("Data")); } } }; registerReceiver(brService, filter); //  bindService(new Intent(this,MainService.class),mConnection,BIND_AUTO_CREATE); Button bt = (Button)findViewById(R.id.buttonSend); bt.setOnClickListener(new OnClickListener() { public void onClick(View v) { //  try { String strResult = iService.UpdateSrv("String from app"); Log.i("AppService",strResult); }catch(RemoteException e){Log.e("AppService",e.getMessage());} } }); } @Override protected void onDestroy() { super.onDestroy(); if(brService!= null){unregisterReceiver(brService);} if(mConnection!= null){unbindService(mConnection);} } } 


Make changes to the service code:

 package ru.blagin.appservice; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; public class MainService extends Service { Intent in = null; @Override public void onCreate() { super.onCreate(); in = new Intent("AppService"); in.putExtra("Data"," ."); sendBroadcast(in); } @Override public IBinder onBind(Intent intent) { return new UpdateService.Stub() { public String UpdateSrv(String strTest) throws RemoteException { strTest = strTest + " and service."; in.putExtra("Data","  ."); sendBroadcast(in); return strTest; } }; } @Override public void onDestroy() { super.onDestroy(); } } 


We start the application and press the button, the test line is sent to the service, then another line is added to the line and the result is output through the methods of the Log class:



Conclusion


I hope this small article will help you further in the future to better understand the mechanisms of interaction and operation of applications in the Android operating system. I wanted to note once again that this text was created exclusively for novice programmers and the main criterion for writing was to answer the question “How to do it?”.

The source code of the application.

Bibliography


  1. Pro Android 3 - Satya Komatineni, Dave MacLean, Sayed Hashimi, 2011
  2. AIDL (Android Interface Definition Language) and Inter-Process Communication (IPC) ( umobisoft ).

Source: https://habr.com/ru/post/139831/


All Articles