intent用途汇总

来源:互联网 发布:男人影视软件下载 编辑:程序博客网 时间:2024/06/06 02:08

1、激活Activity、开启Service、发送Broadcast、访问ContentProvider

激活Activity

Intent intent= new Intent(this, NewActivity.class);startActivity(intent);

2、数据传递

传递 基本数据类型、String、CharSequence

//跳转前,传递数据public void onClick(View view){    Intent intent = new Intent(this, SecondActivity.class);    intent.putExtra("byte", (byte)123);    intent.putExtra("short", (short)256);    intent.putExtra("char", 'c');    intent.putExtra("int", 1000000000);    intent.putExtra("long", 1000000000000000000L);    intent.putExtra("float", 100000000000000000000000000000000000000.0F);    intent.putExtra("double", 1.0);    intent.putExtra("string", "string");    intent.putExtra("charsequence", "charsequence");    startActivity(intent);}//跳转后,获取数据private void showData() {    Intent intent = getIntent();    byte aByte = intent.getByteExtra("byte", (byte)0);    short aShort = intent.getShortExtra("short", (short)0);    char aChar = intent.getCharExtra("char", '0');    int anInt = intent.getIntExtra("int", 0);    long aLong = intent.getLongExtra("long", 0L);    float aFloat = intent.getFloatExtra("float", 0.0F);    double aDouble = intent.getDoubleExtra("double", 0.0);    String string = intent.getStringExtra("string");    CharSequence charsequence = intent.getCharSequenceExtra("charsequence");    System.out.println("byte="+ aByte + ", short=" + aShort + ", char=" + aChar + "\n"+ "int=" + anInt + ", long=" + aLong + ", float=" + aFloat + "\n"+ "double=" + aDouble + ", string=" + string + ", charsequence=" + charsequence);}//显示结果byte=123, short=256, char=cint=1000000000, long=1000000000000000000, float=1.0E38double=1.0, string=string, charsequence=charsequence

传递 Serializable 对象(通过传递 Bundle 的形式写代码,也可以直接传递 Serializable 对象)

Serializable的作用是将数据对象存入字节流当中,在需要时重新生成对象,主要应用是利用外部存储设备保存对象状态,以及通过网络传输对象等,所以能够持续性保存数据。Serializable 的对象是在磁盘上完成的序列化和反序列化,在序列化的时候会产生大量的临时变量,从而引起频繁的GC。

//创建实体类,实现 Serializablepublic class PeopleBean implements Serializable{    private String name;    private int age;    public PeopleBean() {    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "name=" + name + ", age=" + age;    }}//跳转前,创建实体类对象,并数据传递public void onClick(View view){    PeopleBean zhangsan = new PeopleBean();    zhangsan.setName("张三");    zhangsan.setAge(18);    Bundle bundle = new Bundle();    bundle.putSerializable("zhangsan", zhangsan);    Intent intent = new Intent(this, SecondActivity.class);    intent.putExtras(bundle);    startActivity(intent);}//跳转后, 获取数据private void showData() {    Bundle bundle = getIntent().getExtras();    PeopleBean zhangsan = bundle.getSerializable("zhangsan");    System.out.println(zhangsan.toString());}//显示结果name=张三, age=18

传递 Parcelable 对象(通过传递 Bundle 的形式写代码,也可以直接传递 Parcelable 对象)

本质上同 Serializable 一样。只是 Parcelable 的对象是在内存中完成的序列化和反序列化,利用的是连续的内存空间,因此更加高效。但在外界有变化的情况下,Parcelable 不能很好的保存数据的持续性,此时建议使用 Serializable

//创建实体类,实现 Parcelable public class PeopleBean implements Parcelable{    private String name;    private int age;    //用于实例化对象    public PeopleBean() {    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    // 带参构造器方法私用化,本构造器仅供类的方法 createFromParcel 调用    protected PeopleBean(Parcel in) {        name = in.readString();        age = in.readInt();    }    // 必须要创建一个名叫 CREATOR 的常量    public static final Creator<PeopleBean> CREATOR = new Creator<PeopleBean>() {        //重写 createFromParcel 方法,创建并返回一个获得了数据的user对象        @Override        public PeopleBean createFromParcel(Parcel in) {            return new PeopleBean(in);        }        @Override        public PeopleBean[] newArray(int size) {            return new PeopleBean[size];        }    };    @Override    public int describeContents() {        return 0;    }    // 将对象中的属性保存至目标对象 parcel 中    @Override    public void writeToParcel(Parcel parcel, int i) {        parcel.writeString(name);        parcel.writeInt(age);    }    @Override    public String toString() {        return "name=" + name + ", age=" + age;    }}//跳转前,创建实体类对象,并数据传递public void onClick(View view){    PeopleBean zhangsan = new PeopleBean();    zhangsan.setName("张三");    zhangsan.setAge(18);    Bundle bundle = new Bundle();    bundle.putParcelable("zhangsan", zhangsan);    Intent intent = new Intent(this, SecondActivity.class);    intent.putExtras(bundle);    startActivity(intent);}//跳转后,获取数据private void showData() {    Bundle bundle = getIntent().getExtras();    PeopleBean zhangsan = bundle.getParcelable("zhangsan");    System.out.println(zhangsan.toString());}//显示结果name=张三, age=18

3、开启一个新的界面,然后从这个界面获取数据

请求码的值是根据业务需要由自已设定,用于标识请求来源。例如:一个 Activity 有两个按钮,点击这两个按钮都会打开同一个 Activity,不管是哪个按钮打开新 Activity,当这个新 Activity 关闭后,系统都会调用前面 Activity 的onActivityResult(int requestCode, int resultCode, Intent data)方法,并做出相应的业务处理,为了知道点击事件是来自于那个按钮,此时就需要用请求码进行标识。

结果码的值是根据业务需要由自已设定,用于标识数据来源。例如,一个 Activity 中,可能会使用startActivityForResult()方法打开多个不同的 Activity 处理不同的业务,当这些新 Activity 关闭后,系统都会调用前面 Activity 的onActivityResult(int requestCode, int resultCode, Intent data)方法,并做出相应的业务处理。为了知道返回的数据来自于哪个新 Activity,此时就需要用结果码进行标识。

//跳转前,开启新界面public static final int REQUESTCODE = 101;public void onClick(View view){    Intent intent = new Intent(this, SecondActivity.class);    startActivityForResult(intent, REQUESTCODE);}//跳转后,生成实体类对象并设置返回值public static final int RESULTCODE = 200;private void showData() {    PeopleBean zhangsan = new PeopleBean();    zhangsan.setName("张三");    zhangsan.setAge(18);    Bundle bundle = new Bundle();    bundle.putSerializable("zhangsan", zhangsan);    Intent intent = new Intent();    intent.putExtras(bundle);    setResult(RESULTCODE, intent);    finish();}//获取返回的数据@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    super.onActivityResult(requestCode, resultCode, data);    switch (requestCode){        case REQUESTCODE:            if (resultCode == SecondActivity.RESULTCODE){                PeopleBean zhangsan = (PeopleBean) data.getExtras().getSerializable("zhangsan");                System.out.println(zhangsan.toString());            }            break;    }}//显示结果name=张三, age=18

4、开启系统自带应用,如相机、浏览器、短信、电话等,须在清单文件配置action和category及data(mimeType等)

通过查看系统源码,使用隐式意图来开启系统自带应用

拨打电话

//须在清单文件中添加权限//<uses-permission android:name="android.permission.CALL_PHONE" />public void onClick(View view) {    String phonenumber = "133xxxx3333";    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phonenumber));    //自检查权限    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {        return;    }    startActivity(intent);}或者public void onClick(View view) {    //温馨提示:请勿随便拨打“110”,后果自负    Uri uri = Uri.parse("tel:110");    Intent intent = new Intent(Intent.ACTION_DIAL, uri);    startActivity(intent);}

打开网页

public void onClick(View view) {    Uri uri = Uri.parse("http://www.hao123.com");    Intent intent = new Intent(Intent.ACTION_VIEW, uri);    startActivity(intent);}

5、开启其他应用,如打开支付宝、打开微信、打开QQ等

使用隐式意图来开启其他应用
需要设置action和category,
个别时候还需要设置data

打开微信

//首先要判断手机是否装了微信public static boolean isWeixinInstalled(Context context) {    final PackageManager packageManager = context.getPackageManager();// 获取packagemanager    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息    if (pinfo != null) {        for (int i = 0; i < pinfo.size(); i++) {            String pn = pinfo.get(i).packageName;            if (pn.equals("com.tencent.mm")) {                return true;            }        }    }    return false;}//打开微信private void openWeixin() {    Intent intent = new Intent();    ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");    intent.setAction(Intent.ACTION_MAIN);    intent.addCategory(Intent.CATEGORY_LAUNCHER);    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    intent.setComponent(cmp);    startActivity(intent);}public void onClick(View view) {    //首先要判断手机是否装了微信    if (isWeixinInstalled(this)) {        //打开微信        openWeixin();    }}

6、如果应用需要暴露给其他应用使用,也要用到 intent

在清单文件中配置intent-filter
注,将自己的应用暴露给别人使用,是存在风险的,所以这一点请谨慎使用。

原创粉丝点击