In the previous blog post on related topics, we learned how to use action to start activities outside of the current app to handle our business logic, and in this note I briefly describe using componentname to interact with apps outside the current app.
Before introducing component, let's first understand the ComponentName class ComponentName and intent are located under the Android.content package and we can see from the Android official documentation that this class is primarily used to define a visible application component, such as: Activity,service,broadcastreceiver or ContentProvider.
So, how to use componentname to define a component.
This is the ComponentName constructor: ComponentName (String pkg,string CLS)
We know that in an Android application, if you want to describe a component in detail, we need to know the application package name of the component, that is, package= "XXX" under Manifest root node in the Androidmanifest.xml file. Xxxxx. XXXXX ", as well as the full pathname of the component in the application, for activity, the value of the name attribute in the Activity node. So here we are. You can use ComponentName to encapsulate the name of the application package name and component of a component.
We already know that communication between components in Android is often done using intent (Intent), so there's a way to encapsulate a componentname in Intent, and finally we're using the intent to do what we need to implement.
Below we use specific code to describe how to use componentname to help us interact with other applications:
First we want to create two Android apps, Appsend and Appreceiver.
Appreceiver's Androidmainfest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "<span style=" color: #cc0000; " > <strong>package= "com.example.appreceiver" </strong></span> android:versioncode= "1" android: Versionname= "1.0" > <uses-sdk android:minsdkversion= "one" android:targetsdkversion= "/> <" ; application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/A Pp_name "Android:theme=" @style/apptheme "> <activity <strong><span style=" COLOR: #ff 0000; " > android:name= "com.example.appreceiver.MainActivity" </span></strong> android:label= "@string/app _name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application></manifest>
Appsend the start activity fragment in the:
public void button (view view) {<strong><span style= "color: #ff0000;" >componentname cn=new componentname ("Com.example.appreceiver", "com.example.appreceiver.MainActivity"); </ Span></strong>intent Intent = new Intent (); <strong><span style= "color: #ff0000;" >intent.setcomponent (CN); </span></strong>startactivityforresult (Intent, 2);}
Complete case, has been packaged and uploaded to Csdn, if necessary to download, click the Open link