android intent详解

本文详细介绍了Android中的Intent机制,包括其作为消息传递的作用,如何显式或隐式启动Activity和服务,以及如何通过Intent进行数据传递。同时提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

1. 创建一个xml文件,包含一个button当点击时跳转到另一个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);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值