需求是应用A打开应用B的登录界面,在应用B输入QQ号,然后返回给应用A。
打开其他应用activity的核心类是:ComponentName,构造参数有两个,一个是要打开的应用包名,另一个是要打开的activity。
在应用A中打开应用B的代码:
ComponentName componentName = new ComponentName("com.example.droidplugindemo", "com.example.droidplugindemo.LoginActivity");为了能获得返回数据,我们打开时用了startActivityForResult方法,然后重写onActivityResult方法:
Intent intent = new Intent();
intent.setComponent(componentName);
startActivityForResult(intent, 1);
@Override在应用B中返回输入QQ号即可:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK && data!=null)
Log.e("test", "qq=" + data.getStringExtra("qq"));
}
Intent intent = new Intent();在logcat中打印出了应用B返回的QQ号:
intent.putExtra("qq", ((EditText)findViewById(R.id.et)).getText().toString());
setResult(RESULT_OK, intent);
finish();
10-14 14:23:25.268 7154-7154/com.example.droidplugindemo:PluginP08 E/test: qq=55应用A完整代码:
public class MainActivity extends AppCompatActivity {应用B完整代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ComponentName componentName = new ComponentName("com.example.droidplugindemo", "com.example.droidplugindemo.LoginActivity");
Intent intent = new Intent();
intent.setComponent(componentName);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK && data!=null)
Log.e("test", "qq=" + data.getStringExtra("qq"));
}
}
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("qq", ((EditText)findViewById(R.id.et)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
});
}
}
参考: