本文主要讲解Intend在活动之间使用的情况。大致分为以下几种方式:
1.使用显示Intent
2.使用隐式Intent
3.调用系统action的Intent
4.携带参数的Intent
5.带回调的Intent
在说明上面这些知识点之前,先简单为大家简绍一下的作用:
①.当前组件想要执行的操作
②.不同组件之间传递数据(比如:调用拨打电话界面)
③.Intent(Context packageContext,Class
//显示意图
startActivity(new Intent(MainActivity.this,SecondActivity.class));
2.隐式Intent
主要用到了以下这两个标签(可选)
<intent-filter>
<action android:name="com.atguigu.myapplication.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
启动android:name的名字可以自定义,也可以调用系统本来的action。
category:一般都设置为默认的default
//隐式意图(当系统出现两个相同的action的时候,会让用户自行判断调用那个Activity )
startActivity(new Intent("com.atguigu.myapplication.ACTION_START"));
3.调用系统action的Intent
隐式Intent使得多个程序之间的共享功能成为可能.
//intent不同控件之间传递数据
Intent intent = new Intent(Intent.ACTION_VIEW);//(跳转网页)
Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("http://www.baidu.com"));
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
4.携带参数的Intent
使用putExtra()方法暂存数据在intent中
//带参数的启动
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("second","Hi_AndG");
startActivity(intent);
//获得启动该Activity的intent
Intent intent = getIntent();
String second = intent.getStringExtra("second");
Toast.makeText(SecondActivity.this, second , Toast.LENGTH_SHORT).show();
getIntent()得到当前启动活动的Intent
5.带回调的Intent
//带回调的启动
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent,2);
Intent intent1 = new Intent(MainActivity.this, ThirdActivity.class);
startActivityForResult(intent1,3);
//当启动的Activity销毁时,将携带的参数返回给上一级
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 2 :
if(resultCode == RESULT_OK) {
String second = data.getStringExtra("second");
Log.e(TAG, second);
}
break;
case 3:
if(resultCode == RESULT_OK) {
String third = data.getStringExtra("third");
Log.e(TAG, third);
}
break;
}
}
resultCode 一般情况下使用RESULT_OK或RESULT_CANCELED
Intent intent = getIntent();
intent.putExtra("second","Hi_23");
**setResult(RESULT_OK,intent);**//一定要调用该方法
finish();
当你点击back键的时候也想让数据回传给Activity可以重写一下代码
@Override
public void onBackPressed() {
Intent intent = getIntent();
intent.putExtra("second","Hi_23");
setResult(RESULT_OK,intent);
finish();
}