Android--使用活动响应网页

来源:互联网 发布:苹果便签软件关闭 编辑:程序博客网 时间:2024/05/17 16:02

声明

本文承接Android Studio–使用Intent启动活动,使用实例主活动布局如下图:
这里写图片描述
使用隐式Intent,我们不仅能够启动自己程序里的活动,还可以启动其他程序里的活动,这使得Android中多个应用程序之间的功能共享成为了可能,本文主要为设置一个没有主活动的app相应http网页。

一、创建MyHttp的app

1.设置活动布局

设置活动代码如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.example.myhttp.MainActivity">    <TextView        android:textSize="36dp"        android:textColor="@color/colorAccent"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello" /></RelativeLayout>

效果如图:
这里写图片描述

2.活动注册

活动部分代码设为默认,没有修改Android Studio的原始设置,所以此处不讲。活动注册代码如下:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.myhttp">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.VIEW" />                <category android:name="android.intent.category.DEFAULT"/>                <data android:scheme="http"/>            </intent-filter>        </activity>    </application></manifest>

显然,这个app并没有设置主活动,所以在安装到模拟器上的时候同样也没有图标在桌面菜单上显示出来,但是设置的地方是有的。这个MyHttp的作用更像支付宝插件这种东西。

在< data >标签中设置的android:scheme=”http”代表指定了数据的协议必须是http协议,这样没有主活动的MyHttp应用就可以想用http网页操作。
< data >标签主要可以配置以下的内容:

android:scheme//用于指定数据的协议部分,如httpandroid:host//用于指定数据的主机名部分,如www.baidu.comandroid:port//用于指定数据的端口大小,一般跟随在主机名的后边android:path//用于指定主机名和端口之后的部分,如一段网址中跟在域名之后的内容android:mimeType//用于指定可以处理的数据类型,允许使用通用符的方式来指定

只有< data >中的部分与Intent中携带的Data完全一致的时候,当前活动才能够响应Intent。

二、在FirstApp中新建按钮

新建按钮如下:

    <Button        android:id="@+id/button5"        android:text="Open baidu"        android:layout_margin="3dp"        android:textAllCaps="false"        android:background="@color/buttonBg"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />

按钮没有什么特别之处,同样为其设置一个监听器,当点击时生成一个Intent对象,然后系统选择响应的活动进行启动,代码如下:

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

效果如下:
这里写图片描述

0 0