在不同的程序或者项目或者不同的package中,可以通过Intent来彼此沟通交流!!!
两个程序分别是Interactive和test1.
在Interactive和test1里面都有一个TextView和一个Button
假如没有先安装test1的话,点击Interactive里面的Button按钮,提示如下
安装了test1之后,再点击Interactive里的Button,产生的效果如下
Interactive程序的java代码如下
package com.wenming;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class InteractiveActivity extends Activity {
/** Called when the activity is first created. */
private Button button;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=(TextView) findViewById(R.id.tv);
button=(Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent=new Intent();
/*传入的package名称及package名称加class名称*/
intent.setClassName("com.test", "com.test.Test1Activity");
Bundle bundle=new Bundle();
bundle.putString("xixi", "hi,我是来自于InteractiveActivity");
intent.putExtras(bundle);
startActivityForResult(intent, 0);
} catch (Exception e) {
// TODO: handle exception
textView.setText("前安装test程序!!!");
}
}
});
}
}
test1程序的java代码如下
package com.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test1Activity extends Activity {
/** Called when the activity is first created. */
private TextView textView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView=(TextView) findViewById(R.id.tv);
button=(Button) findViewById(R.id.button);
try {
Bundle bundle=getIntent().getExtras();
String string=bundle.getString("xixi");
textView.setText(string);
} catch (Exception e) {
// TODO: handle exception
button.setEnabled(false);
textView.setText("不对!!!");
}
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}