ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Android内容提供器 F8-94-C2-E9-86-AC(2013)4

2020-12-14 13:01:36  阅读:170  来源: 互联网

标签:AC F8 cursor E9 new import android 权限 public


7.1 内容提供器简介

内容提供器:用于在不同的应用程序之间实现数据共享功能,是Android实现跨程序共享数据的标准方式。能够保证被访数据的安全性。

7.2 运行时权限 7.2.1 Android 权限机制详解

1、在学习通知广播那章曾经用过,我们在AndroidManifest.xml中添加权限声明。

2、6.0系统中加入了运行时权限功能,也就是说,用户不需要在安装软件时一次性授权所有的申请的权限,而是可以在使用的过程中对某一项权限申请授权。

3、Android将所有的权限分成了两类:

(1)普通权限:不会直接威胁到用户安全和隐私的权限。对这部分权限的申请,系统会自动帮我们进行授权,无需用户手动操作,例如:网络状态、监听开机广播。

(2)危险权限:可能触及用户隐私、或者对设备安全性造成影响的权限。对于这部分权限的申请,必须由用户手动授权,例如:获取设备联系人信息、定位设备的地理位置的。

4、权限那么多很难记??其实危险权限只有9组24个(见下表),其余都是普通权限。
在这里插入图片描述
5、使用:先看一下是不是危险权限,如果不是,只要在AndroidManifest.xml中添加权限声明。表格中的每个危险权限都属于一个权限组,在运行时权限处理使用的是权限名,但一旦用户同意授权了,那么该权限所对应的权限组中的所有其他权限也会同时被授权。
7.2.2 在程序运行时申请权限
(1)RuntimePermissionTest项目

(2)activity_main.xml

(3)MainActivity.java
package com.example.a7call_phone2021;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private int θ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button makeCall = (Button) findViewById(R.id.make_call);
    makeCall.setOnClickListener(new View.OnClickListener() {
     private void call() {
}
        public void onClick(View v) {
            try {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel: 10086"));
                startActivity(intent);
            }catch ( SecurityException e) {
                e.printStackTrace();
            }
        }

(4)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


package=“com.example.databasetest”>

2、6.0以上的系统中,要进行运行时权限处理。
package com.example.a7call_phone2021;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

public class MyProvider extends ContentProvider {
public static final int TABLE1_DIR = 0;
public static final int TABLE1_ITEM = 1;
public static final int TABLE2_DIR = 2;
public static final int TABLE2_ITEM = 3;
private static UriMatcher uriNatcher;

static {
    uriNatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriNatcher.addURI("com.example.app.provider", "table1", TABLE1_DIR);
    uriNatcher.addURI("com.example.app.provider", "table/#", TABLE1_DIR);
    uriNatcher.addURI("com.example.app.provider ", "table2", TABLE2_DIR);
    uriNatcher.addURI("com.example.app.provider ", "table2/#", TABLE2_ITEM);
}

public MyProvider() {
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    // Implement this to handle requests to delete one or more rows.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public String getType(Uri uri) {
    switch (uriNatcher.match(uri)) {
        case TABLE1_DIR:
            return "vnd.android.cursor.dir/vnd.com.example.app.provider.table1";
        case TABLE1_ITEM:
            return "vnd.android.cursor.item/vnd.com.example.app.provider.table1";
        case TABLE2_DIR:
            return "vnd.android.cursor.dir/vnd.com.example.app.proider.table1";
        case TABLE2_ITEM:
            return "vnd.android.cursor.item/vnd.com.example.app.provider.table2";
        default:
            break;

    }
    return null;
    // TODO: Implement this to handle requests for the MIME type of the data
    // at the given URI.
   // throw new UnsupportedOperationException("Not yet implemented");
}


@Override
public Uri insert(Uri uri, ContentValues values) {
    // TODO: Implement this to handle requests to insert a new row.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public boolean onCreate() {
    // TODO: Implement this to initialize your content provider on startup.
    return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {
    switch (uriNatcher.match(uri)) {
        case TABLE1_DIR:
            //查询table1表中的所有数据
            break;
        case TABLE1_ITEM:
            //查询table1表中的单条数据
            break;
        case TABLE2_DIR:
            //查询table2表中的所有数据
        case TABLE2_ITEM:
            //查询table2表中的单条数据
            break;
        default:
            break;

    }
    // TODO: Implement this to handle query requests from clients.
    throw new UnsupportedOperationException("Not yet implemented");
}


@Override
public int update(Uri uri, ContentValues values, String selection,
                  String[] selectionArgs) {
    // TODO: Implement this to handle requests to update one or more rows.
    throw new UnsupportedOperationException("Not yet implemented");
}

(2)运行结果
第一次运行,会出现选择对话框
在这里插入图片描述
如果选择denied,出现toast提示。选择allow,则进入拨号界面。
在这里插入图片描述

7.3 访问其他程序中的数据

创建自己的内容提供器给我们程序的数据提供外部访问接口。 若一个应用程序通过内容提供器对其数据提供了外部访问接口,那么任何其他应用程序都可以对这部分数据进行访问。
7.3.1 ContentResolver 用法
1、通过Context.getContentResolver() 获得该类的实例,ContentResolver中提供了一系列方法对数据进行CRUD操作。
2、这些CRUD操作的方法不接受表名,接收的是内容Uri。
内容Uri:为内容提供器中的数据提供了唯一的标识符。
组成; -authority:为了区分不同的程序,一般采用程序包名来命名; -path:为了区分同一程序不同的表,通常会添加在authority后面。 Ur的标准格式:content://com.example.app.provider/table1
3、查询功能实现
uri-指定查询谋和应用程序下的某张表
projection-指定查询的列名
selection-where的查询条件
selectionArgs-为where中的占位符提供具体的值
sortOder-查询结果的排序方式
(2)把数据从cursor中读取出来
if(cursor!=null){
while (cursor.moveToNext()){
String column1=cursor.getString(cursor.getColumnIndex(“column1”));
int column2=cursor.getInt(cursor.getColumnIndex(“column1”));
}
cursor.close();
4、增加数据
ContentValues values=new ContentValues();
values.put(“clumn1”,“text”);
values.put(“clumn2”,“1”);
getContentResolver().insert(uri, values);
5、更新数据

ContentValues values=new ContentValues();
values.put(“clumn1”,"");
getContentResolver().update(uri, values, “clumn1=? and clumn2=?”,new String[]{“text”,1});
6、删除数据
getContentResolver().delete(uri, values, “clumn2=?”,new String[]{1});
7.3.2 读取系统联系人
1、读取系统联系人

(1)新建项目:ContactsTest

(2)在模拟器里新建两个联系人信息

(3)layout_main.xml:放入一个listView

<ListView
    android:id="@+id/contacts_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

(4)MainActivity.java

package com.example.a7call_phone;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
ListconactsList=new ArrayList<>();
private ArrayAdapter adapter;
private int θ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView contactsView = (ListView) findViewById(R.id.contacts_vie);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.
            simple_list_item_1, conactsList);
    //adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,conactsList);
    contactsView.setAdapter(adapter);
    if (ContextCompat.checkSelfPermission(this,Manifest.permission.
            READ_CONTACTS)!=PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.
                READ_CONTACTS},1);

} else {
        readContacts();
    }

}

private void readContacts() {
    Cursor cursor=null;
    try {
        //查询联系人数据
        cursor = getContentResolver().query(ContactsContract.CommonDataKinds.
                Phone.CONTENT_URI, null, null, null,
                null);
        if (cursor !=null)
        while (cursor.moveToNext()) {
            //获取联系人姓名
            String displayName = cursor.getString(cursor.getColumnIndex
                    (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            //获取联系人手机号
            String number = cursor.getString(cursor.getColumnIndex
                    (ContactsContract.CommonDataKinds.Phone.NUMBER));
            conactsList.add(displayName + "\n" + number);
        }
       adapter.notifyDataSetChanged();
    } catch (Exception exception) {

        exception.printStackTrace();
    }finally {
        if (cursor !=null){
          cursor.close();
        }
    }
}

private void call(){
            try {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel: 10086"));
                startActivity(intent);
            } catch (SecurityException e) {
                e.printStackTrace();

            }
    };

public void onRequestPermissionsResult(int requestCode,String[] permissions,
                                       int[] grantResults){
    switch (requestCode) {
        case 1:
            if (grantResults.length > θ && grantResults[θ] == PackageManager.PERMISSION_GRANTED){
            call();
            }else{
                Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
            }
            break;
        default:
    }
}

}

(5)AndroidManifest.xml:修改权限

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

<application
    android:allowBackup="true"

(6)运行结果
在这里插入图片描述

标签:AC,F8,cursor,E9,new,import,android,权限,public
来源: https://blog.csdn.net/weixin_51451150/article/details/111162031

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有