Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom intent targeting a specific package

Say my app is "A", I start an activity of an app "B" using custom intent from the app "A". It works fine as I would want it to. The code I use is, in manifest of app "B":

<activity
        android:name=".mysecondAct"
        android:label="@string/title_activity_second" >
        <intent-filter>
            <action android:name="com.example.intent.action.Dream" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

In my activity from app "A", I start app "B" with,

Intent i =new Intent("com.example.intent.action.Dream");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

Now, how do I specify a specific package to which the intent should be sent to so that, only that app receives the intent and start the activity? The reason is, I have a list of package and the user chooses which one to call.

like image 845
Vijai Avatar asked Jan 11 '15 06:01

Vijai


2 Answers

Use the ComponentName class like below:

Intent intent = new Intent();

intent.setComponent(new ComponentName("com.example1", "com.example1.MyExampleActivity1"));

startActivity(intent);

Pls note that the first argument is not the package name of the class; it is the package name of the application---the package attribute of the manifest element in that application's AndroidManifest.xml.

If you know the name of the activity to be started (not the class) then you can do something like this:

Class<?> claz = null;

if(StringClassname != null) {

    try {

        claz = Class.forName(StringClassname );

    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    }

}

Intent intent = new Intent(this, claz);

startActivity(intent);

And, in case you don't even know the activity name and the corresponding class, then I guess it becomes a candidate for using broadcast i.e. From you AppA, you should be broadcasting..and have broadcast receiver in AppB,AppC etc with corresponding filters..

Edit: Given that you are just aware of the package name and the intent action name, try creating your intent like this:

Intent i = new Intent();

i.setAction("com.example.intent.action.Dream");

i.setPackage(packageName);

startActivity(i);
like image 147
Uncaught Exception Avatar answered Oct 28 '22 21:10

Uncaught Exception


So the fix was very simple. I just set the package in intent to which package my intent should be passed. The code is:

Intent i =new Intent("com.example.intent.action.Dream");
i.setPackage("com.package.to.start"); //The package name of the app to which intent is to be sent
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
like image 44
Vijai Avatar answered Oct 28 '22 22:10

Vijai