2019年9月

Android中常用的应用都会大量使用网络,比如QQ、微信、访问网页等等。通过使用网络,可以展示网页,发起Http请求获取数据或提交数据。

WebView控件

有时我们可能需要让我们自己的应用展示网页,我们可以使用Android内置的控件WebView

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = (WebView)findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://www.baidu.com");
    }
}

布局文件:

<?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">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

由于使用了网络功能,需要声明网络权限。在AndroidManifest.xml添加android.permission.INTERNET:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jyoryo.app.android.study">

    <uses-permission android:name="android.permission.INTERNET" />

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

- 阅读剩余部分 -

内容提供器Content Provider用于不同程序之间进行数据共享:允许其它程序访问操作提供内容提供器的程序,同时保证提供被访问的数据的安全性。

内容提供器Content Provider一般有两种用法:

  • 使用其他现有提供内容提供器的程序来读取和操作该程序的数据;
  • 自身程序创建内容提供器供其他程序读取和操作自身程序的数据,即对外提供接口。

比如常用的电话簿、短信、媒体库等都提供了内容提供器供其他程序读取和操作数据。

内容提供器Content Provider基本用法

通过Context中的getContentResolver()获取ContentResolver类的实例来访问其他程序的内容提供器的数据,进行相关CRUD操作。相关方法与SQLiteDatabase基本相同,只不过方法参数有些不同。

  • insert():添加数据;
  • update():更新数据;
  • delete():删除数据;
  • query():查询数据。

ContentResolverCRUD操作不接受表名,而是使用Uri参数(内容URI)。内容URI给内容提供器提供了唯一标志符,它是有两部分组成:authoritypath

  • authority:用于区分应用程序,一般为了更好的区分,都会采用程序包名再加上provider来命名。比如程序的包名com.demo.app,那么该程序的authority可以命名为com.demo.app.provider
  • path:用于区分同一程序中不同表,通常都会添加在authority后面。比如程序存在2张表table1table2,对应的path就可以分别命名为/table1/table2
  • 内容URI:是将上面的authoritypath进行组合,然后再在头部加上协议声明。比如content://com.demo.app.provider/table1content://com.demo.app.provider/table2

- 阅读剩余部分 -