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.
 

Rusty

Well-Known Member
Licensed User
OK, after following desolatesoul's advice and messing around with some of the manifests, I've made this work.
Since there is no sample code, I'm uploading my test code for anyone who wishes to use this feature.

REQUESTOR: Build configuration Package Name: thisapp.b4a.intentrequestor
Manifest:
AddManifestText(
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14"/>
<supports-screens android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
'End of default text.
AddActivityText(Main, <intent-filter>
<action android:name="thisapp.b4a.intentrequestor.CALLBACK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>)
Code:
B4X:
#Region  Project Attributes
    #ApplicationLabel: IntentRequestor
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Button1 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("1")
    Activity.Title="IntentRequester"
End Sub

Sub Activity_Resume
    Dim in As Intent
    in = Activity.GetStartingIntent
    If in <> Null Then
        If in.HasExtra("Settings") Then
            Dim xtra As String = in.ExtrasToString
            LogColor("            REQUESTOR "  & xtra, Colors.Blue)
        End If
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Button1_Click
    Dim in As Intent
    in.Initialize("thisapp.b4a.intentprovider.REQUEST","")
    in.AddCategory("android.intent.category.DEFAULT")
    in.PutExtra("Callback","thisapp.b4a.intentrequestor.CALLBACK")
    in.PutExtra("GetSettings","True")
    StartActivity(in) 'Or StartService(returnIntent)
End Sub

PROVIDER: Build configuration Package Name: thisapp.b4a.intentprovider
Manifest:
AddManifestText(
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="14"/>
<supports-screens android:largeScreens="true"
android:anyDensity="true"/>)
AddActivityText(Main, <intent-filter>
<action android:name="thisapp.b4a.intentprovider.REQUEST" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")

'End of default text.
Code:
B4X:
#Region  Project Attributes
    #ApplicationLabel: IntentProvider
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("1")
    Activity.Title="IntentProvider"
    Label1.Text=DateTime.Time(DateTime.now)

End Sub

Sub Activity_Resume
Log("PROVIDER ******************************")  
    Dim in As Intent
     in = Activity.GetStartingIntent
    If in <> Null Then
        If in.HasExtra("GetSettings") Then
            Dim callback As String = in.GetExtra("Callback")
LogColor("            PROVIDER: GetStartingIntent", Colors.Red)
LogColor("                came from: " & callback, Colors.red)
           SendSettings(in)
           Activity.Finish
           Return
        End If
     End If
End Sub

Sub SendSettings(in As Intent)
    Dim returnIntent As Intent
    returnIntent.Initialize(in.GetExtra("Callback"),"")
    returnIntent.AddCategory("android.intent.category.DEFAULT")
    returnIntent.PutExtra("Settings", "Hello")
    returnIntent.PutExtra("Successful","True")
    StartActivity(returnIntent) 'Or StartService(returnIntent)
    LogColor("            PROVIDER "  & returnIntent.ExtrasToString, Colors.red)
  
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Compile and install both programs on a device. The Requestor has a button, touch it to test the code. Watch the Logging for results.
I hope this helps someone
Rusty
 

wenzelww

Member
Licensed User
Hi Rusty,
thank's for putting this together it helps me a lot. I tried to use this example with a wearable device. The mobile device is the IntendRequestor, the wearable is the IntentProvider it compiles but an error occurs when sending. the Request intent
(No Activity found to handle intent).
Do you know how to do it with wearable?

Wilhelm
 

Rusty

Well-Known Member
Licensed User
What wearable device are you using? (brand, model, Android O/S)
Rusty
 

wenzelww

Member
Licensed 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
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

brunnlechner

Member
Licensed 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:

Similar Threads

  • Locked
  • Article
Android Tutorial Intent Based Camera
Replies
48
Views
23K
Replies
120
Views
159K
  • Locked
  • Article
Android Tutorial GPS tutorial
Replies
310
Views
230K
Top