Android学习随笔(2)------Intent基本用法

来源:互联网 发布:网络科技部个体户名称 编辑:程序博客网 时间:2024/06/17 19:37

学习流程来自《第一行代码》(第二版)
一个Android应用不可能只有一个活动 活动与活动之间的切换,使用的是Intent。

显示Intent

主要实现的功能为:主活动命名为FirstActivity,点击Button跳转到SecondActivity活动。
在FirstActivity中创建一个button1

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button    android:id="@+id/button_1"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="Button_1"    /><!--  id=给当前元素定义一个唯一标识符            layout_width=当前元素的宽度 与父元素一样宽            layout_height=当前元素的高度 刚好显示文字            text=元素中显示的文字内容--></LinearLayout>    <!--创建的first_layout时候选择了LinearLayout为根元素!-->

Exler
在AndroidManifest.xml中注册FirstActivity和SecondAndroid页面

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.yezhou.activitytest">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity            android:name=".FirstActivity"            android:launchMode="singleTask"            android:label="This is FirstActivity">            <intent-filter> <!-- 不是主活动不需要配置 -->                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".SecondActivity">        </activity>    </application></manifest>

利用FirstActivity中button的鼠标点击事件来打开SecondActivity 这里就要用到Intent。

Intent有很多个构造参数,比较简单的是Intent(Context packageContext, Class cls),第一个参数指的是 提供一个启动活动的上下文,也就是当前的java文件FirstActivity.this,第二个就是要跳转的活动,这里是SecondActivity.class。专门用于启动活动的方法为startActivity(),传入已经创建好的Intent对象即可。

 Button button1 = (Button) findViewById(R.id.button_1);    // 找到定义元素 button1.setOnClickListener(new View.OnClickListener() {    // 为Button1注册一个监听器     @Override     public void onClick(View v){         Intent intent = new Intent(FirstActivity.this,SecondActivity.class);    // 启动活动的上下文,要启动活动的class         startActivity(intent);    // 启动活动    !--显式Intent     } }

这时运行虚拟机,点击button就可以跳转到SecondActivity。

隐式Intent

不明确指定由哪个Activity去响应FirstActivity里的按钮点击事件。
(为了更好的理解可以创建一个ThirdActivity,由它去响应此事件)

先在AndroidManifest.xml中对三个Activity进行注册:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.yezhou.activitytest">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity            android:name=".FirstActivity"            android:launchMode="singleTask"            android:label="This is FirstActivity">            <intent-filter> <!-- 不是主活动不需要配置 -->                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".SecondActivity">        </activity>        <activity android:name=".ThirdActivity">            <intent-filter>                <action android:name="com.example.yezhou.activitytest.ACTION_START" />                <category android:name="android.intent.category.DEFAULT" /> <!-- 只有<action><category>同时匹配上Intent中指定的action和category时这个活动才能响应该Intent -->            </intent-filter>        </activity>    </application></manifest>

修改FirstActivity中button的点击事件

button1.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v){        Intent intent = new Intent("com.example.yezhou.activitytest.ACTION_START");        startActivity(intent);    // 自动将默认category添加    }}

运行,这时你会发现点击按钮打开的是ThirdActivity
应为对ThirdActivity的注册中category属性为

<category android:name="android.intent.category.DEFAULT" />

这是一种默认的category,在调用startActivity()方法时会自动将其添加。


可以在AndroidManifest.xml文件中修改SecondActivity的注册文件:

<activity android:name=".SecondActivity"            android:launchMode="singleInstance">    <intent-filter>        <action android:name="com.example.yezhou.activitytest.ACTION_START" />        <category android:name="com.example.yezhou.activitytest.MY_CATEGORY" />    </intent-filter></activity>

接着在button的点击事件中

Button button1 = (Button) findViewById(R.id.button_1);    // 找到定义元素button1.setOnClickListener(new View.OnClickListener() {    // 为Button1注册一个监听器    @Override    public void onClick(View v){        Intent intent = new Intent("com.example.yezhou.activitytest.ACTION_START");        intent.addCategory("com.example.yezhou.activitytest.MY_CATEGORY");    // 添加一个指定的category值                                                       startActivity(intent);    }}

运行,这时SecondActivity会来响应我们的点击事件,因为只有SecondActivity的action,category的值才能与button中指定的对得上号,所以由SecondActiviy来隐式响应。

有的时候我们还会调用其他的软件来响应接下去的事件,比如说打开一个网页这时只要修改FirstActivity.java中button的点击事件即可。

Button button1 = (Button)findViewById(R.id.button_1);button1.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View view) {        Intent intent = new Intent(Intent.ACTION_VIEW);        intent.setData(Uri.parse("http://www.baidu.com"));        startActivity(intent);    }}             

调用系统的浏览器来打开百度。

不仅如此还可以响应别的软件的网页请求
在AndroidManifest.xml中的intent-filteri标签的data属性设置要用来响应其他软件Intent的http协议。
这里我们来实现点击FirstActivity中的button由SecondActivity来响应它。
在AndroidManifest.xml中SecondActivity的标签里面加上

<intent-filter>    <action android:name="android.intent.action.VIEW"/>    <data android:scheme="http" /></intent-filter>

这时我们运行程序,点击button
Exler
我们会发现TWO来响应我们http的请求了。
除了http协议外还可以指定很多其他协议

Button button1 = (Button) findViewById(R.id.button_1);button1.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v){        Intent intent = new Intent(Intent.ACTION_VIEW);        intent.setData(Uri.parse("tel:10000"));           startActivity(intent);    }}

Exler

响应一个data uri为http的activity geo表示地理位置 tel表示拨打电话

传递数据的活动切换

向下一个活动传递参数

在button的点击事件中

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);    intent.putExtra("extra_data","Hello SecondActivity");    // 传递一个值给下一个activitystartActivity(intent);    // 启动活动  

“extra_data”是键,而后面那个参数是值

在SecondActivity页面来输出“Hello SecondActivity”

    super.onCreate(savedInstanceState);    setContentView(R.layout.second_layout);    Intent intent = getIntent();    Log.d("SecondActivity",intent.getStringExtra("extra_data"));    // 显示上一个活动传递进来的值

Exler

返回数据给上一个活动
有了向下传递那么也必定有向上传递

在FirstActivity中修改button打开SecondActivity 的方式

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);startActivityForResult(intent,1);    // 期望在活动销毁时能够返回一个结果给上一个活动 由于 SecondActivity是用此方法启动的,所以被销毁之后会回调上一个活动的onActivityResult方法,所以需要重写此方法startActivity(intent);    // 启动活动

使用startActivityForResult()方法来启动SecondActivity,请求码只要是一个唯一的值即可。
在SecondActivity活动中添加一个button

Button button2 = (Button)findViewById(R.id.button_2);button2.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View view) {        Intent intent = new Intent();        intent.putExtra("data_return","Hello FirstActivity");    // 需要传递的数据        setResult(RESULT_OK,intent);    // 用于向上一个activity返回数据的        finish();    }}

虽然我们还是创建了一个Intent,但是这个intent并没有明确指定,点击了button后该切换到哪个界面。
这里的intent仅用于传递数据,调用setResult()方法 第一个参数用于向上一个活动返回处理结果,一般RESULT_OK或RESULT_CANCELED,第二个参数则把带有数据的 intent传递回去。finish()方法来销毁当前活动。
应为FirstActivity是被回掉的对象,那么需要重写它的onActivityResult()方法

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        switch (requestCode) {            case 1:                if (resultCode == RESULT_OK)                  Log.d("FirstActivity",data.getStringExtra("data_return"));                break;            default:        }    }

第一个参数就是我们在启动那个被销毁的活动时传入的请求码(判断数据来源),第二个参数即是在SecondActivity返回数据时的处理结果(是否成功),第三个参数就是intent。
运行先点击button来到SecondActivity,接着点击SecondActivity中的button
Exler
可以看到FirstActivity成功的接收到了SecondActivity传递的值。

但如果用户是在SecondActivity直接点击了back键来返回FirstActivity的需要重写SecondActivity中的onBackPressde()方法

@Override    public void onBackPressed() {        Intent intent = new Intent();        intent.putExtra("data_return","Hello FirstActivity");        setResult(RESULT_OK);        finish();    }

此博文为个人学习笔记,仅供个人学习使用,希望对大家有帮助。

原创粉丝点击