Intent类

原创 2016年05月30日 21:52:31

一、简介

Intent类是协调应用中四大组件通讯的,负责对应用中一次操作的动作、涉及的数据以及附加信息进行描述

.setAcition() 描述动作 .setData() 描述涉及的数据 .setType() 描述类型

二、引用Intent的方式

1、显示(直接)调用

通过指定的Activity的类名来显式引用Intent

①方法一

  public class Activity_Intent extends AppCompatActivity {
        Buttonb mToAnother_Activity_Btn;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_intent_layout);
            mToAnother_Activity_Btn = (Button) findViewById(R.id.toanother_activity_btn);
            //============显示调用=========
            mToAnother_Activity_Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   Intent intent=new Intent(Activity_Intent.this,Activity_Intent_Another.class);
				   startActivity(intent);
                }
            });

        }
    }

②方法二

   public class Activity_Intent extends AppCompatActivity {
        Buttonb mToAnother_Activity_Btn;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_intent_layout);
            mToAnother_Activity_Btn = (Button) findViewById(R.id.toanother_activity_btn);
            //============显示调用=========
            mToAnother_Activity_Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setComponent(new ComponentName(Activity_Intent.this, Activity_Intent_Another.class));
                }
            });

        }
    }

2、隐式调用

方法一

通过隐式调用系统应用

public class Activity_Intent extends AppCompatActivity {
    Button mDialphone_Btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_layout);
        mDialphone_Btn = (Button) findViewById(R.id.dialphone_btn);
        //==========隐式调用
        mDialphone_Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //==========调用系统拨号				
                intent.setAction(Intent.ACTION_DIAL);
                //intent.setAction(Intent.ACTION_CALL);
                //使用ACTION_CALL时,需要在AndroidManifest中添加相应的权限,如<use permission="android.permission.CALL_PHONE"
                Uri uri = Uri.parse("tel:123");
                intent.setData(uri);
                startActivity(intent);
            }
        });
    }
}

通过隐式调用媒体资源时,如音乐,要通过s.etDataAndType()同时获取资源位置和设置类型,若通过.setData();.setType();设置,则可能出现无法运行的情况。


②方法二:自定义Activity<action>属性隐式调用

第一步:在AndroidManifest.xml中对应的<activity></activity>中添加<action>和<category>属性

第二步:在当前Activity中添加相关操作的语句

public class Activity_Intent extends AppCompatActivity {
    Button mYs_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_layout);
        mYs_btn = (Button) findViewById(R.id.ys_btn);
        mYs_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("sjl.intent.aciton.Active");
                startActivity(intent);
            }
        });
    }
}

三、通过Intent在Activity之间传递参数

1、通过Intent传递基本数据类型、String类

{
	//=============CurrentActivity存入
	intent intent=new Intent();
	//intent.putExtra(String name,Object value);
	//存入Extra中,参数1 String name相当于key,values 可以为任何基本数据类型,也可以为String等
	intent.putExtra("KEY","CurrentActivity")
}

{
	//==============AnotherActivity取值
	Intent intent=getIntent();
	String key=intent.getString("KEY");
	//通过String name,获取相对应的值
}

2、通过Intent传递Bundle对象

mSendMsgByBundleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("NAME", mNameEdit.getText().toString());//放入Key为"NAME"的数据
                bundle.putString("BORN", mBornYearEdit.getText().toString());//放入Key为"BORN"的数据
                bundle.putString("ADDR", mAdressEdit.getText().toString());//放入Key为"ADDR"的数据
                bundle.putBoolean("SEX", sex);//放入Key为"SEX"的数据
                Intent intent = new Intent(EnteringMessageActivity.this, ReceiveMessageActivity.class);
                intent.putExtra("BUNDLE", bundle);
                intent.putExtra("TYPE", 1);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                int requestCode = 193;
                startActivityForResult(intent, requestCode);
            }
        });

  public void recMsgByBundle(Intent intent) {
        //通过getIntent.getBundleExtra获取buunle实例,来保证bundle是传过来的bundle
        Bundle bundle = intent.getBundleExtra("BUNDLE");
        mRecName_Txt.setText(getResources().getString(R.string.name) + bundle.getString("NAME"));
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + bundle.getString("BORN"));
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + bundle.getString("ADDR"));
        mSex_Txt.setText(getResources().getString(R.string.sex) + (bundle.getBoolean("SEX") ? "男" : "女"));
    }

3、传递实现Serializable接口的类的对象

//===========类实现Serializable接口,通过Intent.putEtra()实现Activity之间传递对象
        mSendMsgBySer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EnteringMessageActivity.this, ReceiveMessageActivity.class);
                PersonMsgSer person = new PersonMsgSer();
                person.setName(mNameEdit.getText().toString());
                person.setBorn(mBornYearEdit.getText().toString());
                person.setAddr(mAdressEdit.getText().toString());
                person.setSex(sex);
                intent.putExtra("SER", person);
                intent.putExtra("TYPE", 2);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                int requestCode = 194;
                startActivityForResult(intent, requestCode);
            }
        });

public void recMsgBySer(Intent intent) {
        PersonMsgSer person = (PersonMsgSer) intent.getSerializableExtra("SER");
        mRecName_Txt.setText(getResources().getString(R.string.name) + person.getName());
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + person.getBorn());
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + person.getAddr());
        mSex_Txt.setText(getResources().getString(R.string.sex) + (person.isSex() ? "男" : "女"));
    }

4、传递实现Parcelable接口的类的对象

mSendMsgByPar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EnteringMessageActivity.this, ReceiveMessageActivity.class);
                //根据需要重载要传递的实现Percelable接口的类的构造方法
                PersonMsgPar person = new PersonMsgPar(mNameEdit.getText().toString(),
                        mBornYearEdit.getText().toString(), mAdressEdit.getText().toString(), sex);
                intent.putExtra("PAR", person);
                intent.putExtra("TYPE", 3);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                Log.v("Par", mNameEdit.getText().toString() + "," + mBornYearEdit.getText().toString() + "," + mAdressEdit.getText().toString());
                int requestCode = 195;
                startActivityForResult(intent, requestCode);
            }
        });
public void recMsgByPar(Intent intent) {
        PersonMsgPar person = intent.getParcelableExtra("PAR");
        mRecName_Txt.setText(getResources().getString(R.string.name) + person.getName());
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + person.getBorn());
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + person.getAddr());
        mSex_Txt.setText(getResources().getString(R.string.sex) + (person.isSex() ? "男" : "女"));
    }

四、Activity参数的回传(回传值)

1、跳转Activity时,语句使用startActivityForResult(),并且重写当前Activity的onActivityResult()方法;

2、跳转到的Activity中使用setResult()语句

下面是一个具体的Demo:

public class EnteringMessageActivity extends AppCompatActivity {
    Button mSendMessageBtn, mSendMsgByBundleBtn, mSendMsgBySer, mSendMsgByPar;
    TextView mShowReturnValue;
    EditText mNameEdit, mBornYearEdit, mAdressEdit;
    String[] message = new String[3];
    RadioGroup sexRadio;
    boolean sex = true;
    int number = 1;//判断生日日期输入框文本是增加还是减少

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entering_message_layout);
        mSendMessageBtn = (Button) findViewById(R.id.sendmessage_btn);
        mNameEdit = (EditText) findViewById(R.id.name_et);
        mBornYearEdit = (EditText) findViewById(R.id.born_year_et);
        mAdressEdit = (EditText) findViewById(R.id.address_et);
        sexRadio = (RadioGroup) findViewById(R.id.sex_radio);
        mSendMsgByBundleBtn = (Button) findViewById(R.id.sendmessagebybundle_btn);
        mSendMsgBySer = (Button) findViewById(R.id.sendmessagebyser_btn);
        mSendMsgByPar = (Button) findViewById(R.id.sendmessagebypar_btn);
        mShowReturnValue = (TextView) findViewById(R.id.show_return_txt);
        //=============传递"SEX"信息,若sex为true则为“男性”,反之“女性”
        sexRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.man_radio:
                        sex = true;
                        break;
                    case R.id.woman_radio:
                        sex = false;
                        break;
                }
            }
        });
        //===========通过Intent实现Activity之间的信息传递
        mSendMessageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("scxh.intent.action.ReceiveMag");//通过自定义的action属性隐师调用
                message[0] = mNameEdit.getText().toString();
                message[1] = mBornYearEdit.getText().toString();
                message[2] = mAdressEdit.getText().toString();
                //  Log.v("输入的姓名", message[0]);
                System.out.println("输入的姓名:" + message[0]);
                //  Log.v("输入的出生日期", message[1]);
                // Log.v("输入的地址", message[2]);
                intent.putExtra("MESSAGE", message);
                intent.putExtra("SEX", sex);
                intent.putExtra("TYPE", 0);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                int requestCode = 192;
                startActivityForResult(intent, requestCode);
            }
        });
        //===============通过Bundle实现Activity之间的信息传递,传递Bundle对象
        mSendMsgByBundleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("NAME", mNameEdit.getText().toString());
                bundle.putString("BORN", mBornYearEdit.getText().toString());
                bundle.putString("ADDR", mAdressEdit.getText().toString());
                bundle.putBoolean("SEX", sex);
                Intent intent = new Intent(EnteringMessageActivity.this, ReceiveMessageActivity.class);
                intent.putExtra("BUNDLE", bundle);
                intent.putExtra("TYPE", 1);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                int requestCode = 193;
                startActivityForResult(intent, requestCode);
            }
        });
        //===========类实现Serializable接口,通过Intent.putEtra()实现Activity之间传递对象
        mSendMsgBySer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EnteringMessageActivity.this, ReceiveMessageActivity.class);
                PersonMsgSer person = new PersonMsgSer();
                person.setName(mNameEdit.getText().toString());
                person.setBorn(mBornYearEdit.getText().toString());
                person.setAddr(mAdressEdit.getText().toString());
                person.setSex(sex);
                intent.putExtra("SER", person);
                intent.putExtra("TYPE", 2);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                int requestCode = 194;
                startActivityForResult(intent, requestCode);
            }
        });
        //===========类实现Parcelable接口,通过Intent.putEtra()实现Activity之间传递对象
        mSendMsgByPar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EnteringMessageActivity.this, ReceiveMessageActivity.class);
                //根据需要重载要传递的实现Percelable接口的类的构造方法
                PersonMsgPar person = new PersonMsgPar(mNameEdit.getText().toString(),
                        mBornYearEdit.getText().toString(), mAdressEdit.getText().toString(), sex);
                intent.putExtra("PAR", person);
                intent.putExtra("TYPE", 3);//传入int参数,使ReceiveMessageActivity根据这个参数判断调用什么方法
                Log.v("Par", mNameEdit.getText().toString() + "," + mBornYearEdit.getText().toString() + "," + mAdressEdit.getText().toString());
                int requestCode = 195;
                startActivityForResult(intent, requestCode);
            }
        });
        mBornYearEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.v("测试输入前", "start:" + start + ",after:" + after);
                number = after;//若字符串长度增加,则after为1;反之为0
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.v("测试输入中", "start:" + start + ",before:" + before);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String ymd = mBornYearEdit.getText().toString();
                //-------------输入前四位数字的时候自动添加"年",第七位添加"月",,第十位添加"日"
                if (number == 1 && s.length() == 4) {
                    mBornYearEdit.setText(ymd + "年");
                    Selection.setSelection((Spannable) mBornYearEdit.getText(), s.length() + 1);
                } else if (number == 1 && s.length() == 7) {
                    mBornYearEdit.setText(ymd + "月");
                    Selection.setSelection((Spannable) mBornYearEdit.getText(), s.length() + 1);
                } else if (number == 1 && s.length() == 10) {
                    mBornYearEdit.setText(ymd + "日");
                    Selection.setSelection((Spannable) mBornYearEdit.getText(), s.length() + 1);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String obj = null;
        switch (requestCode) {
            case 192:
                obj = "Intent";
                break;
            case 193:
                obj = "Bundle";
                break;
            case 194:
                obj = "Serializable";
                break;
            case 195:
                obj = "Parcelable";
                break;
        }
        Log.v("标签1", obj);
        if (data == null) {
            mShowReturnValue.setText("暂无内容");
        } else {
            mShowReturnValue.setText(obj + "\r\n用户信息:\r\n" + data.getStringExtra("RECNAME") + "\r\n" + data.getStringExtra("RECBORN") + "\r\n" +
                    data.getStringExtra("RECADDR") + "\r\n" + data.getStringExtra("RECSEX"));
        }
    }
}

public class ReceiveMessageActivity extends AppCompatActivity {
    TextView mRecName_Txt, mRecYear_Txt, mRecAddress_Txt, mSex_Txt;
    Button mSaveBtn, mCancelBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_message_layout);
        mRecName_Txt = (TextView) findViewById(R.id.rec_name_txt);
        mRecYear_Txt = (TextView) findViewById(R.id.rec_year_txt);
        mRecAddress_Txt = (TextView) findViewById(R.id.rec_address_txt);
        mSex_Txt = (TextView) findViewById(R.id.rec_sex_txt);
        mSaveBtn = (Button) findViewById(R.id.rec_save_btn);
        mCancelBtn = (Button) findViewById(R.id.rec_cancel_btn);
        Intent intent = getIntent();
        switch (intent.getIntExtra("TYPE", 0)) {
            case 0:
                recMsgByIntent(intent);
                break;
            case 1:
                recMsgByBundle(intent);
                break;
            case 2:
                recMsgBySer(intent);
                break;
            case 3:
                recMsgByPar(intent);
                break;
        }
        mSaveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                int resultCode = 100;
                intent.putExtra("RECNAME", mRecName_Txt.getText().toString());
                intent.putExtra("RECBORN", mRecYear_Txt.getText().toString());
                intent.putExtra("RECADDR", mRecAddress_Txt.getText().toString());
                intent.putExtra("RECSEX", mSex_Txt.getText().toString());
                setResult(resultCode, intent);
                finish();
            }
        });
        mCancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public void recMsgByIntent(Intent intent) {
        mRecName_Txt.setText(getResources().getString(R.string.name) + intent.getStringArrayExtra("MESSAGE")[0]);
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + intent.getStringArrayExtra("MESSAGE")[1]);
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + intent.getStringArrayExtra("MESSAGE")[2]);
        mSex_Txt.setText(getResources().getString(R.string.sex) + (intent.getBooleanExtra("SEX", true) ? "男" : "女"));
    }

    public void recMsgByBundle(Intent intent) {
        //通过getIntent.getBundleExtra获取buunle实例,来保证bundle是传过来的bundle
        Bundle bundle = intent.getBundleExtra("BUNDLE");
        mRecName_Txt.setText(getResources().getString(R.string.name) + bundle.getString("NAME"));
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + bundle.getString("BORN"));
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + bundle.getString("ADDR"));
        mSex_Txt.setText(getResources().getString(R.string.sex) + (bundle.getBoolean("SEX") ? "男" : "女"));
    }

    public void recMsgBySer(Intent intent) {
        PersonMsgSer person = (PersonMsgSer) intent.getSerializableExtra("SER");
        mRecName_Txt.setText(getResources().getString(R.string.name) + person.getName());
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + person.getBorn());
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + person.getAddr());
        mSex_Txt.setText(getResources().getString(R.string.sex) + (person.isSex() ? "男" : "女"));
    }

    public void recMsgByPar(Intent intent) {
        PersonMsgPar person = intent.getParcelableExtra("PAR");
        mRecName_Txt.setText(getResources().getString(R.string.name) + person.getName());
        mRecYear_Txt.setText(getResources().getString(R.string.bornyear) + person.getBorn());
        mRecAddress_Txt.setText(getResources().getString(R.string.address) + person.getAddr());
        mSex_Txt.setText(getResources().getString(R.string.sex) + (person.isSex() ? "男" : "女"));
    }
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

038集-Intent类的重要成员变量

  • 2015年10月25日 15:14
  • 28.61MB
  • 下载

intent传递类内容

  • 2015年07月06日 17:21
  • 910KB
  • 下载

Android intent跳转工具类

/** * 进行页面跳转的工具 * * @author chen.lin * */ public class IntentUtil { private static final ...
  • lovoo
  • lovoo
  • 2016年05月11日 23:20
  • 1899

Android 学习(26)Intent 分类

  • 2016年03月21日 19:55
  • 635KB
  • 下载

Intent实现分享功能工具类

  • 2016年10月17日 15:41
  • 5KB
  • 下载

侧滑菜单HorizontalScrollView,类中如何使用intent跳转

布局文件main.xml

Android Intent传递泛型类

  • 2014年07月04日 10:18
  • 1.29MB
  • 下载

Android突破三:Intent类

Intent类 Jiangdg_VIP http://blog.csdn.net/u012637501 1.概述:     Intent直译是指意图,目的的意思,在Android中,它...

Android中使用Intent进行窗体切换,并且传值和自定义类的对象详解 .

转自http://blog.csdn.net/newflypig/article/details/6246705  在Android中,Intent对象负责各个Activity窗口之间的切换,同时他更...

Android类-Intent

Intent是执行某操作的抽象描述。最常用的是启动Activity。 可以用于通过 startActivity(Intent)启动Activity, 通过startService(Intent)或b...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Intent类
举报原因:
原因补充:

(最多只允许输入30个字)