ComponentName的使用及相關介紹

原文出處:http://blog.csdn.net/u012702547/article/details/49557905

ComponentName,顧名思義,就是組件名稱,通過調用Intent中的setComponent方法,我們可以打開另外一個應用中的Activity或者服務。

實例化一個ComponentName需要兩個參數,第一個參數是要啓動應用的包名稱,這個包名稱是指清單文件中列出的應用的包名稱:

第二個參數是你要啓動的Activity或者Service的全稱(包名+類名),代碼如下:

啓動一個Activity:

[java] view plain copy
 print?
  1. Intent intent = new Intent();  
  2.             intent.setComponent(new ComponentName("com.example.otherapp",  
  3.                     "com.example.otherapp.MainActivity2"));  
  4.             startActivity(intent);  



啓動一個Service:

[java] view plain copy
 print?
  1. Intent it = new Intent();  
  2. it.setComponent(new ComponentName("com.example.otherapp",  
  3.         "com.example.otherapp.MyService"));  
  4. startService(it);  



注意

如果你要的啓動的其他應用的Activity不是該應用的入口Activity,那麼在清單文件中,該Activity節點一定要加上Android:exported="true",表示允許其他應用打開,對於所有的Service,如果想從其他應用打開,也都要加上這個屬性:

[java] view plain copy
 print?
  1. <service  
  2.     android:name="com.example.otherapp.MyService"  
  3.     android:exported="true" >  
  4. </service>  
  5.   
  6. <activity  
  7.     android:name="com.example.otherapp.MainActivity2"  
  8.     android:exported="true" >  
  9. </activity>  

對於除了入口Activity之外的其他組件,如果不加這個屬性,都會拋出“java.lang.SecurityException: Permission Denial.....”異常


那麼爲什麼入口Activity不用添加這個屬性就可以被其他應用啓動呢?我們來看一段入口Activity的註冊代碼:

[java] view plain copy
 print?
  1. <activity  
  2.     android:name=".MainActivity"  
  3.     android:label="@string/app_name" >  
  4.     <intent-filter>  
  5.         <action android:name="android.intent.action.MAIN" />  
  6.   
  7.         <category android:name="android.intent.category.LAUNCHER" />  
  8.     </intent-filter>  
  9. </activity>  

入口Activity和普通Activity唯一不同的地方就是入口Activity多了一個過濾器,對於包含了過濾器的組件,意味着該組件可以提供給外部的其他應用來使用,它的exported屬性默認爲true,相反,如果一個組件不包含任何過濾器,那麼意味着該組件只能通過指定明確的類名來調用,也就是說該組件只能在應用程序的內部使用,在這種情況下,exported屬性的默認值是false。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章