Android 调用另外一个apk中的activity

2014-11-24 09:22:23 · 作者: · 浏览: 0

系统提供了很多可以直接调用的Activity,通过指定的Intent就可以调用,比如打开搜索的:


  Java代码


  Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);


  intent.putExtra(SearchManager.QUERY,"searchString")


  startActivity(intent);


  Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);


  intent.putExtra(SearchManager.QUERY,"searchString")


  startActivity(intent);


  Intent.ACTION_WEB_SEARCH是一个字符串,是“搜索”这个Activity的标识,extra是传给这个activity的一些数据。发送出这个intent之后,系统根据action字符串Intent.ACTION_WEB_SEARCH知道了是要调用哪个activity,如果有重名,会弹出一个选择对话框。然后打开此activity,实现想要做的事情。


  那么,我们自己怎么来实现呢。


  Xml代码


  < intent-filter>


  < action Android:name="chroya.foo"/>


  < category android:name="android.intent.category.DEFAULT"/>


  < /intent-filter>


  < intent-filter>


  < action android:name="chroya.foo"/>


  < category android:name="android.intent.category.DEFAULT"/>


  < /intent-filter>


  然后安装。安装完毕之后,你会发现,系统中找不到这个程序。别急,它确实安装在手机里面了,但是因为他不是main的,所以系统不会把他当做Application的入口程序。


  而要想打开这个activity,只有知道它名字的人才可以。跟系统的intent一样使用。它的名字定义为"chroya.foo",所以,这里用这个字符串就可以调用它了:


  Java代码


  Intent intent = new Intent("chroya.foo");


  startActivity(intent);


  Intent intent = new Intent("chroya.foo");


  startActivity(intent);


  我用刚才举的那个系统的intent说明,它的activity里面使用 getIntent().getBundleExtra(SearchManager.QUERY)来接收传递进来的搜索字符串参数。而这个 SearchManager.QUERY是关键字。如果要自己实现这种功能,只需要定义好关键字,然后从BundleExtra中取就行了。