在Android中Intent是我们经常遇到的,因为往往我们需要传递数据到不同的Activity中,尤其是在没有后台数据的时候,我们经常会使用intent来测试自己的代码逻辑,下文中将会涉及标题中所有的知识点,请仔细观察!
相关Blog
最初的我 ~
- 作为一个程序员,代码是我们最直观的表达
- 认真看,不要嫌多,其实每个知识点都很简短有效><
2019/11/7 优化
基本认知
基本功能
- Activity之间的数据传递
- 数据回写
- ActionBar菜单实现
- 销毁前数据保存
- Intent意图(电话,网络)
基本使用
原文件
-
intent.putExtra(key,value)
key一般是String,值为 java八大基本数据类型及对应的数组,String及对应的数组, Serializable 及对应的数组等
-
intent.putExtras(bundle)
-
intent.putExtra(key,bundle)
目标文件
- intent.getXXXExtra(key)获取值
- bundle=intent.getExtras()
- bundle=intent.getExtras(key)
各种场景下Intent数据传递
String传值
- activity A
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("myTag","你好,亲爱的姑娘");
startActivity(intent);
- activity B
String tag = getIntent().getStringExtra("myTag");
int传值
- activity A
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("myTag",666);
startActivity(intent);
- activity B
//这里的第二个参与0为默认值,表示如果activityA 传过来的值如果没空,那么默认返回tag = 0
int tag = getIntent().getIntExtra("myTag",0);
Bundle传值
这种方式就是将数据封装到 Bundle 中然后把 Bundle 对象调用 Intent 的 putExtra 方法然后传递过去,
Bundle 类默认也是已经实现了 Parcelable 接口的,所以可以传递 Bundle 对象
- activity A
// 创建一个Bundle对象封装数据
Bundle data = new Bundle();
data.putInt("age",18);
data.putString("name","Jack");
intent.putExtra("data",data);
- activity B
Bundle data = getIntent().getBundleExtra("data");
int id = data.getInt("age");
String name = data.getString("name");
传递 Map 集合数据
Map接口及他的实现类默认是没有实现序列化的接口的,我们要想传递 Map 就要让 Map 实现序列化接口,我们可以自定义一个类,以HashMap为例吧,我们的类就叫 SerializableHashMap 吧,然后让定义一个 Map 变量作为成员属性并实现序列化接口,这样我们的类就可以进行传递了,SerializableHashMap 的实现如下:
- SerializableHashMap
public class SerializableHashMap implements Serializable {
private HashMap<String, String> map;
public SerializableHashMap() {
}
public SerializableHashMap(HashMap<String, String> map) {
this.map = map;
}
public HashMap<String, String> getMap() {
return map;
}
public void setMap(HashMap<String, String> map) {
this.map = map;
}
}
- ActivityA
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Jack");
map.put("age", 18);
SerializableHashMap sMap = new SerializableHashMap();
// 将map数据添加到封装的sMap中
sMap.setMap(map);
Bundle bundle = new Bundle();
bundle.putSerializable("map", sMap);
Intent intent = new Intent(ActivityA.this,ActivityB.class);
intent.putExtras(bundle);
startActivity(intent);
- ActivityB
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
SerializableHashMap sMap = (SerializableHashMap) bundle.get("map");
HashMap<String, Object> map = sMap.getMap();
List传递
如果传递实体Bean,必须实现序列化 - Serializable
主要借鉴了 这儿 ~
如果我们要传递的 List 集合,我们可以把 List 强转成 Serializable 类型,List 默认是实现了 Serializable 接口的,
但是注意 List 的泛型类也必须要实现了 Serializable 接口,基本类型及包装类就不用了
- activity A
User user1 = new User();
user1.setName("Jack");
user1.setAge(18);
User user2 = new User();
user2.setName("Marry");
user2.setAge(20);
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
Intent intent = new Intent(ActivityA.this,ActivityB.class);
intent.putExtras("list",(Serializable)list);
startActivity(intent);
- activity B
Intent intent = getIntent();
List<User> list = (List<User>) getIntent().getSerializableExtra("list");
传递Bitmap的几种简单方式
借鉴与此,传递应该有问题
方式1
场景 :有两个activity,A,B,从A进入B。先在A中将Bitmap写进去
- activity A
Resources res=getResources();
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.ic_launcher);
Bundle b = new Bundle();
b.putParcelable("bitmap", bmp);
Intent intent = new Intent(this, MainActivity2.class);
intent.putExtras(b);
startActivity(intent);
- activity B
Intent intent=getIntent();
Bundle b=intent.getExtras();
Bitmap bmp=(Bitmap) b.getParcelable("bitmap");
方式2
- activity A
Resources res=getResources();
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes=baos.toByteArray();
Bundle b = new Bundle();
b.putByteArray("bitmap", bytes);
Intent intent = new Intent(this, MainActivity2.class);
intent.putExtras(b);
startActivity(intent);
- activity B
Intent intent=getIntent();
Bundle b=intent.getExtras();
byte[] bytes=b.getByteArray("bitmap");
Bitmap bmp=BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
项目实践
项目结构图
Activity逻辑代码
MainActivity
package com.example.intentdemo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private TextView mMain;
private TextView mMainData;
private TextView mInter;
private TextView mPhone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//如果onsave中在销毁钱有数据的话,这里会重现数据
if (savedInstanceState != null) {
String object = (String) savedInstanceState.get("savekey");
}
// 放置点击事件
initdata();
// 为了,方便区分,这里单独设置 onclick的Intent意图传递
mMain.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecoundActivity.class);
intent.putExtra("name", "MainActivity传递过来的数据");
startActivityForResult(intent, 1);
}
});
}
/**
* 事件处理
* */
private void initdata() {
mMain = (TextView) findViewById(R.id.tv_main);
mMainData = (TextView) findViewById(R.id.tv_main_data);
mPhone = (TextView) findViewById(R.id.tv_telephone);
mInter = (TextView) findViewById(R.id.tv_inter);
mPhone.setOnClickListener(this);
mInter.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_inter:
Intent interintent = new Intent(Intent.ACTION_VIEW);
interintent.setData(Uri.parse("http://www.baidu.com"));
startActivity(interintent);
break;
case R.id.tv_telephone:
String phonenumber = "10086";
// Intent intentphone = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phonenumber)); 意义相同,链式方便但容易乱
Intent intentphone = new Intent();
intentphone.setAction(Intent.ACTION_CALL);
intentphone.setData(Uri.parse("tel:"+phonenumber));
startActivity(intentphone);
break;
default:
break;
}
}
// 获取Secound的数据
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 25) {
String secoundExtra = data.getStringExtra("intentdata");
mMainData.setText(secoundExtra);
Toast.makeText(MainActivity.this, secoundExtra, 0).show();
Toast.makeText(MainActivity.this, "stringExtra测试触发", 0).show();
}
}
// 销毁前保存的数据
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String SaveData = "This is save data ";
outState.putString("savekey", SaveData);
}
/**
* ActionBar菜单测试.注意:先要创建菜单,然后才可以设置事件处理。 这里要注意的是:不论eclipse还是As 我们都需要在meau中设置xml的item样式
* */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_add:
Toast.makeText(MainActivity.this, "add测试触发", 0).show();
break;
case R.id.item_remove:
Toast.makeText(MainActivity.this, "remove测试触发", 0).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
SecoundActivity
package com.example.intentdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SecoundActivity extends Activity {
private EditText mEt;
private TextView mTx;
private String mainInent;
private TextView mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secound);
mEt = (EditText) findViewById(R.id.et_text);
mTx = (TextView) findViewById(R.id.tv_text);
mButton = (TextView) findViewById(R.id.tv_button);
//上层数据
initdata();
//Edit数据获取
Editdata();
}
//获取用户输入传回上层
private void Editdata() {
mButton.setOnClickListener(new OnClickListener() {
private String editdata;
@Override
public void onClick(View v) {
editdata = mEt.getText().toString();
if(editdata.length()==0){
Toast.makeText(SecoundActivity.this, "请输入内容", 0).show();
}else{
Intent intent = new Intent(SecoundActivity.this,MainActivity.class);
// Bundle bundle = new Bundle();
// bundle.putString("intentdata", editdata);
// intent.putExtras(bundle); 意义相同只是二次包装而已
intent.putExtra("intentdata", editdata);
Toast.makeText(SecoundActivity.this,editdata, 0).show();
setResult(25, intent);
finish();
}
}
});
}
/**
* 获取MainActivity的Intent数据传递
* */
private void initdata() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
mainInent = (String)bundle.get("name");
//点击之后数据替换
mTx.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTx.setText(mainInent);
}
});
}
}
布局代码
activity.main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:id="@+id/tv_main"
android:layout_height="40dp"
android:text="点击之后data传递" />
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:id="@+id/tv_main_data"
android:layout_height="40dp"
android:text="Secound回传数据" />
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:id="@+id/tv_telephone"
android:layout_height="40dp"
android:text="telephone" />
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:id="@+id/tv_inter"
android:layout_height="40dp"
android:text="inter" />
</LinearLayout>
activity_secound
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="center"
android:text="Secound回顾,点击之后数据替换"
android:gravity="center"
android:id="@+id/tv_text"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/et_text"
android:gravity="center"
android:hint="Please Edit"
android:maxEms="1"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="center"
android:text="数据回显测试"
android:gravity="center"
android:id="@+id/tv_button"
/>
</LinearLayout>