Android Tutorial [TUTORIAL] Inter-app Communication with Intents

DISCLAIMER:
This tutorial is written without testing code. There may be bugs, but try to understand the process, not copy the code.


An intent is a way for different applications to communicate at run time. It can be used to pass messages between activities and make them do actions. Using it with startActivity targets the intent to an activity. Broadcast intents are broadcast to all activities, and any applications with an intent filter can listen for it and perform an action.

Explicit Intents: The target component (service or activity) is known. (For e.g. an intent to the browser)

Implicit Intents: The system will determine which activity is best to launch this intent. (For e.g. Share intents)

More information on intents:
Intents and Intent Filters | Android Developers


In this example we have two apps.
- The Provider, that contains the data we need
- The Requester, that will request the data via Intent


Step 1: Setup the Provider to be able to receive intents
This can be done in two ways:
1. Explicitly setting the component, and making it visible by setting exported=true
2. Defining your own intent filter

We will do the second way since it is more structured.

We set up an intent filter to trigger our activity in the Provider.
In the manifest editor add the following, for the Activity you want to trigger.
You can also use a service (use AddServiceText instead)

B4X:
AddActivityText(Main, <intent-filter>
   <action android:name="com.maximussoft.myprovider.REQUEST" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>)

Step 2: Code the Provider to return the data
When using an Activity,

B4X:
Sub Activity_Resume
 Dim in as Intent
 in = Activity.GetStartingIntent
 If in <> null Then
    If In.HasExtra("GetSettings") Then
       SendSettings(in)
       Activity.Finish
       Return
    End If
 End If
End Sub

...so far so good...
however do you see the problem here?
no? come on think harder
How does the Providor know which app to send the data back to? The Intent by default has no information about the Calling package.

Again, there are two (simpler) ways to deal with this
1. Add information about the Requestor in the intent extras so we can call it back
2. Use StartActivityForResult. This allows you to get the calling package name, but infact you do not even need it. You can just return the result as an intent back to the Requestor Activity.

However, this is the point where you pause and think about what your apps need to do. Are they working silently in the background? Or do they show a dialog at some point?

For now, we go with the first option, and assume that the Requestor sends us an intent action in the extras.
So in SendSettings we do,
B4X:
Sub SendSettings(in as Intent)
   Dim returnIntent as Intent
   returnIntent.Initialize(in.GetExtra("Callback"),"")
   returnIntent.AddCategory("android.intent.category.DEFAULT")
   returnIntent.PutExtra("Settings",someGlobalSettings)
   returnIntent.PutExtra("Successful","True")
   StartActivity(returnIntent) 'Or StartService(returnIntent)
End Sub
Make note of how the return intent is initialized with the Callback field from the original recevied intent.

3. Set up the Requester
As you may have noticed, the Requester needs to be set up in the same way except for some minor differences. First you set up the manifest, with a different intent filter:
B4X:
 AddActivityText(Main, <intent-filter>
   <action android:name="com.maximussoft.myrequestor.CALLBACK" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>)

4. Code the Requester to request the data/settings
This can be anywhere in your code, but if its settings you want to request, it will probably be in activity create or resume. The thing to note here is how we initialiaze the intent with the ACTION of the PROVIDER. And we send the CallBack i.e. the intent of the REQUESTER as the CALLBACK so the provider can send us back the data.

B4X:
Sub RequestSettings
   Dim in as Intent
   in.Initialize("com.maximussoft.myprovider.REQUEST","")
   in.AddCategory("android.intent.category.DEFAULT")
   in.PutExtra("Callback","com.maximussoft.myrequestor.CALLBACK")
   in.PutExtra("GetSettings","True")
   StartActivity(in) 'Or StartService(returnIntent)
End Sub

5. Code the Requester to accept the data
Again this code is very similar to the Provider except that it gets the data
B4X:
 Sub Activity_Resume
 Dim in as Intent
 in = Activity.GetStartingIntent
 If in <> null Then
    If In.HasExtra("Settings") Then
         AcceptSettings 'Do something here with your settings
    End If
 End If
End Sub

Points to note:
While I dont consider intents to be very advanced, it can be quite overwhelming for newbies, so do your research.

There are many ways to do things and combinations of services/activities can make things complicated.

You can add permissions on your intent filters, this way Plugin apps need to have your permission in their manifest. This helps in *some* access control, mainly you can list all apps that can access your app/settings/data.
To see this in operation you can look at my apps that plugin to each other Cloudpipes and PhoneBackup.
If I get time I may write a sample otherwise not.
 

wenzelww

Member
Licensed User
Longtime User
Just wanted to let you know that I could find a working solution inside the Wearable Datalayer threat:

static - More complex but means you can receive messages at any time
Add the following text to the Manifest Editor
<code>AddApplicationText(
<service android:name="barxdroid.wearabledatalayer.ListenerService"
android:label="Wearable Listener">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>)
</code>
Then add a service called 'WearListenerService to your project and in the service module, use code like this.
<code>
Sub Process_Globals
Dim WL As WearableListener
End Sub
Sub Service_Start (StartingIntent As Intent)
WL.Initialize("WL")
WL.HandleIntent(StartingIntent)
End Sub
Sub WL_MessageReceived(SourceNodeID As String, RequestID As Int, msgPath As String, Data As String)
ToastMessageShow(Data, False)
End Sub
</code>


Wilhelm
 

brunnlechner

Member
Licensed User
Longtime User
Hello,
if I change to android:targetSdkVersion="26", I get the error:

java.lang.IllegalArgumentException: Service Intent must be explicit: Intent....


B4X:
    Dim in As Intent
    in.Initialize("thisapp.b4a.intentprovider.REQUEST","")
    StartService(in)


Franz
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User

brunnlechner

Member
Licensed User
Longtime User
B4X:
in.SetPackage("provider.app")
'assuming that this is the target app package name

Thanks Erel, you're the best - that's how it works perfectly again.
 
Last edited:
Top