intent是一种消息传递机制,可以用于应用程序内,或者应用程序间,主要用于,
1. 显式或隐式启动activity,service,
2. 启动service或activity执行某个动作,如拨打电话(Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:12345678")), 最后再执行startActivity(intent))
3. 广播某个事件,应用程序可以注册Broadcast Receivergo 监听和响应这些广播的intent
一、显示启动Activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button android:id="@+id/startNewIntent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="startNewActivity" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/startNewIntent"
android:text="intent activity" />
</LinearLayout>
2. 创建相应的activity类,并为button添加事件,实现activity跳转
public class IntentActivity extends Activity{
private Button startNewIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intent_activity);
init();
}
private void init(){
startNewIntent = (Button)findViewById(R.id.startNewIntent);
startNewIntent.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
Intent intent = new Intent(IntentActivity.this, ChildActivity.class);
startActivity(intent);
}})
;
}
}
然后自己随便添加一个简单的childActivity测试一下就可以了
二、隐式启动activity
1. 隐式的启动activity可以让匿名的应用程序组件响应请求的动作,即系统选择可以执行请求动作的应用程序,当有多个应用程序都能响应请求动作时,弹出列表让用户选择需要使用的应用程序
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:12345678"));
startActivity(intent);
在上面的基础之上,稍加修改,(修改按钮事件)
常用的action有:ACTION_GET_CONTENT, ACTION_MAIN, ACTION_EDIT等等,action不同,对应的需要传递的数据类型2. 也不同,在此不一一列举,有需要的可以查阅一下API(其实有些我也不太清楚,嘿嘿)
在启动一个新的Activity的时候,可能通过extra属性添加需要传递的数据,extra是key,value形式,
Intent intent = new Intent(IntentActivity.this, ChildActivity.class);
intent.putExtra("username", "erfan");
startActivity(intent);
然后在另一个界面接收的时候,可以这样
childActivity = (TextView)findViewById(R.id.childActivity);
Intent intent = this.getIntent();
String userName = intent.getStringExtra("username");
childActivity.setText(userName);