我是iOS 转Android 的,做一些自己的学习记录.
Intent
Intent 有很多的作用,由于初次尝试Android,暂时知道Intent可以用于界面之前的切换就ok了。
显示Intent
//初始化Intent, 表示从FirstActivity 到 SecondActivity
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
//执行 intent实例
startActivity(intent); //若要返回上一个类,可点击右上角back。或者手动代码 finish();销毁当前activity
隐式Intent
//在AndroidManifest.xml中添加
<activity android:name = ".SecondActivity">
<intent - filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT" />
</intent - filter>
</activity>
//当action 和 category同时匹配成功才能启动下一个activity,这里能调用时因为有android.intent.category.DEFAULT默认category
Intent intent = new Intent("com.example.activitytest.ACTION_START");
//这样调用category需要在AndroidManifest.xml中添加 <category android:name="android.intent.category.My_CATEGORY" />
//Intent.addCategory("com.example.activitytest.My_CATEGORY");
startActivity(intent);
调用系统浏览器
//intent的action是Intent.ACTION_VIEW
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
新建一个ThirdActivity
<activity android:name=".ThridActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http"/>
//intent 响应data 标签中满足http协议的activity,这样执行上面调用浏览器intent 就会出现选择列表
</intent-filter>
</activity>
打电话
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
向下一个activity传递数据
//FirstActivity
String data = "Hello SecondActivity";
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("extra_data",data);//extra_data 是键,data是要传递的值,这里data是字符串
startActivity(intent);
//SecondActivity中获取值
Intent intent = getIntent();
String data = intent.getStringExtra("extra_data");//获取传过来的值
Log.v("SecondActivity",data);//打印
返回数据给上一个活动
//FirstActivity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent,1);
//SecondActivity
Intent intent = new Intent();
intent.putExtra("data_return","Hello First");//putExtra(键,值)
setResult(RESULT_OK,intent);
finish();
//FirstActivity 重写onActivityResult 来接收数据
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String returnData = data.getStringExtra("data_return");
Log.v("FirstActivity", returnData);
}
}
}
//SecondActivity 通过back键回到FirstActivity
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
intent.putExtra("data_return","Hello First");
setResult(RESULT_OK,intent);
finish();
}
//通过左上actionBar 返回按钮
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
}
return super.onOptionsItemSelected(item);
}