Android中有Context的概念,有了Context就可以做很多事情,如打开activity、发送广播、打开文件夹和数据库、获取
classLoader、获取资源等等。
那么能获取到手机上其他应用的Context吗?
能!有了其他应用的Context,几乎就可以做其他应用能做的任何事。
示例:
下面这个类是手机上的某个应用
- package com.example;
- import android.app.Activity;
- import android.util.Log;
- public class InvokedActivity extends Activity {
- public void print(String msg) {
- Log.i("IA", msg);
- }
- }
下面代码是我的应用,去调用上面那个类的print方法
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button android:id="@+id/invoke"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="调用其它应用方法" />
- </LinearLayout>
- package com.invoke;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Toast;
- public class TestActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- findViewById(R.id.invoke).setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- invokeOtherPackage();
- }
- });
- }
- private void invokeOtherPackage() {
- try {
- /*
- CONTEXT_INCLUDE_CODE: 包含代码,可以执行此包中的代码。
- CONTEXT_IGNORE_SECURITY: 忽略安全警告,不加有此功能不能用,会得到安全警告。
- */
- Context otherPackageContext = this.createPackageContext("com.example", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
- if (otherPackageContext != null) {
- //载入类
- Class clazz = otherPackageContext.getClassLoader().loadClass("com.example.InvokedActivity");
- if (clazz != null) {
- //创建实例
- Object obj = clazz.newInstance();
- //获取并执行print方法
- clazz.getMethod("print", String.class).invoke(obj, "Ask in TestActivity");
- } else {
- showMessage("没有获取到类");
- }
- } else {
- showMessage("没有获取到其它包上下文");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void showMessage(String message) {
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
- }
- }
当点击按钮时,会调用其他应用的方法(InvokedActivity的print方法),该方法输入如下

可能你在想,是不是只有当两个应用是同一个keystore签名才可以相互调用?当不同keystore签名就不能相互调用?
错,不同keystore签名一样可以调用,这个我测试过了。
不要使用此功能来破坏其他应用,厚道点为好。