zoukankan      html  css  js  c++  java
  • 内容提供者之获取短信

      Android中每个APP在数据存储上是隔离的,比如A应用想要访问B应用的数据库是无法直接访问。但是google提供了内容提供者的组件,内容提供者会对外暴露一些对本地数据的访问的接口。B应用如果实现了内容提供者接口并将该接口对外发布,则A应用则可以访问B中的某些数据了。

      这里以获取短信为例。

    布局文件


    布局文件很简单,通过button来触发click事件

    <?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:text="获取短信"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="click"/>
    </LinearLayout>

    Activity


    在activity中主要使用ContentResolver对象,该对象是对内容提供者的访问接口。可以通过该对象与ContentProvider发生数据的交互

    package xidian.dy.com.chujia;
    
    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    
    
    public class MainActivity extends AppCompatActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        public void get(View v){
            ContentResolver cr = getContentResolver();
            //第一个参数是内容提供者的标识
            //系统有很多内容提供者,内容系统者如果想要被别人访问,则需要在清单文件中注册自己
            //sms是短息应用中提供者的标识,content是协议,就如同http一样
            Cursor cursor = cr.query(Uri.parse("content://sms"), new String[]{"address", "date","body", "type"}, null, null, null);
            if(cursor != null){
                while(cursor.moveToNext()){
                    String address = cursor.getString(0);
                    long date = cursor.getLong(1);
                    String body = cursor.getString(2);
                    int type = cursor.getInt(3);
                    System.out.println(address + date + body + type);
                }
                cursor.close();
            }
        }
    
        public void insert(View v){
            ContentResolver cr = getContentResolver();
            ContentValues values = new ContentValues();
            values.put("address", 95555);
            values.put("type", 1);
            values.put("body", "收到100万");
            values.put("date", System.currentTimeMillis());
            cr.insert(Uri.parse("content://sms"),values);
        }
    }

    有内容提供者ContentProvider实现了query方法,这个查询才有结果,否则的话调用会返回null。

  • 相关阅读:
    谈URL中末尾斜杠对SEO的影响
    ORDER BY一个较高级的用法
    MYSQL5.5 提示 Mysq error:Cannot load from mysql.proc
    mysql 数据库信息泄露
    [转]PclZip简介与使用
    通过telnet命令查看memcache运行状态
    [转载]PHP上传问题总结(文件大小检测,大文件上传)
    Silex 基于Symfony2组件的微型框架
    [转]推荐一些不错的计算机书籍
    [转]Beanstalkd简介(job生命周期)
  • 原文地址:https://www.cnblogs.com/xidongyu/p/5754900.html
Copyright © 2011-2022 走看看