第十单元 内容提供者

大城市里の小女人 提交于 2019-11-27 05:58:32

读取短信java代码

package com.example.ap.EP2;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.provider.Telephony;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.example.ap.MyPhone;
import com.example.ap.R;

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

public class AP2Activity extends AppCompatActivity {
    private List<MyMessage> list=new ArrayList<>();
    private SQLiteDatabase db;
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ap2);
        lv=findViewById(R.id.ep2_listView);
        MMHelper mh = new MMHelper(this, "sm.db", null, 1);
        db=mh.getReadableDatabase();

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_SMS,Manifest.permission.READ_CONTACTS},101);
        }else{
            readMessage();
        }
    }

    public void click(View view) {
        Cursor cursor = db.rawQuery("select * from messages", null);
        if( cursor!=null) {
            while (cursor.moveToNext()) {
                String message2 = cursor.getString(cursor.getColumnIndex("address"));
                String address2 = cursor.getString(cursor.getColumnIndex("message"));
                ep2MyAdapter aaa = new ep2MyAdapter(this, list);
                lv.setAdapter(aaa);
            }
        }else{
            Toast.makeText(this, "游标为空。", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if( requestCode==101&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
            readMessage( );
        }
    }
    //获取短信。
    private void readMessage() {
        Uri uri = Telephony.Sms.CONTENT_URI;
        ContentResolver cr = getContentResolver();
        Cursor query = cr.query(uri, new String[]{Telephony.Sms.ADDRESS, Telephony.Sms.BODY}, null, null, null);
        if( query==null){
            Toast.makeText(this, "没有读取到短信。", Toast.LENGTH_SHORT).show();
        }else{
            while (query.moveToNext()) {
                String address = query.getString(query.getColumnIndex(Telephony.Sms.ADDRESS));
                String message = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
                Toast.makeText(this, "address:"+address+"\nmessage:"+message, Toast.LENGTH_SHORT).show();
                MyMessage myPhone = new MyMessage();
                MyMessage myMessage = myPhone.setAddress(address).setBody(message);
                list.add(myMessage);
                db.execSQL("insert into messages values(?,?)",new Object[]{address,message});
            }

        }
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EP2.AP2Activity"
    android:orientation="vertical"
    >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ap2_button"
        android:text="点击获取手机短信。"
        android:onClick="click"
        />
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ep2_listView"
        >

    </ListView>
</LinearLayout>

自定义适配器

package com.example.ap.EP2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.ap.R;

import java.util.List;

public class ep2MyAdapter extends BaseAdapter {
    private Context con;
    private List<MyMessage> list;

    public ep2MyAdapter(Context con, List<MyMessage> list) {
        this.con = con;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private MyId mi;
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if( convertView==null){
            convertView= LayoutInflater.from(con).inflate(R.layout.ep2_layout,null);
            mi=new MyId();
            TextView address = convertView.findViewById(R.id.ep2_layout_address);
            mi.address=address;
            mi.message=convertView.findViewById(R.id.ep2_layout_message);
            convertView.setTag(mi);
        }else{
            mi= (MyId) convertView.getTag();
        }
        mi.address.setText(list.get(position).getAddress());
        mi.message.setText(list.get(position).getBody());
        return convertView;
    }
    class MyId{
        private TextView address;
        private TextView message;
    }
}

helper类

package com.example.ap.EP2;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MMHelper extends SQLiteOpenHelper {
    public MMHelper(Context context,String name,  SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table messages(address varchar(60),message varchar(60))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

自定义短信对象

package com.example.ap.EP2;

public class MyMessage {
    private String body;
    private String address;

    public String getBody() {
        return body;
    }

    public MyMessage setBody(String body) {
        this.body = body;
        return this;
    }

    public String getAddress() {
        return address;
    }

    public MyMessage setAddress(String address) {
        this.address = address;
        return this;
    }

    @Override
    public String toString() {
        return "MyMessage{" +
                "body='" + body + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

获取手机联系人

自定义手机类

package com.example.ap;

public class MyPhone {
    private String name;
    private String phone;

    public String getName() {
        return name;
    }

    public MyPhone setName(String name) {
        this.name = name;
        return this;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "MyPhone{" +
                "name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

自定义Helper类

package com.example.ap;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyHelper extends SQLiteOpenHelper {
    public MyHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table linkman(name varchar(20),phone varchar(40))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

包含了一个按钮的主类

package com.example.ap;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    private List<MyPhone> list=new ArrayList<>();
    private SQLiteDatabase db;

    private Button textClick;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyHelper mh = new MyHelper(this, "link.db", null, 1);
        db=mh.getReadableDatabase();
        //初始化控件
        textClick = (Button) findViewById(R.id.text_click);
        listView = (ListView) findViewById(R.id.list_view);
        //判断手机版本,二十三之前不需要动态申请权限
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS,Manifest.permission.CALL_PHONE},101);
        }else{
            LinkMan();
        }
        //按钮点击获取数据库中的联系人
        textClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor cursor = db.rawQuery("select * from linkman",null);
                list.clear();
                while (cursor.moveToNext()) {
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String phone = cursor.getString(cursor.getColumnIndex("phone"));
                    MyPhone mp=new MyPhone();
                    mp.setName(name).setPhone(phone);
                    list.add(mp);
                }
                //类部类设置联系人。
                listView.setAdapter(new BaseAdapter() {
                    @Override
                    public int getCount() {
                        return list.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return list.get(position);
                    }

                    @Override
                    public long getItemId(int position) {
                        return position;
                    }

                    private MyId mi;
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        if( convertView==null){
                            mi=new MyId();
                            convertView= LayoutInflater.from(MainActivity.this).inflate(R.layout.mylayout,null);
                            mi.name = convertView.findViewById(R.id.ml_name);
                            mi.phone = convertView.findViewById(R.id.ml_phone);
                            convertView.setTag(mi);
                        }else{
                            mi= (MyId) convertView.getTag();
                        }
                        mi.name.setText(list.get(position).getName());
                        mi.phone.setText(list.get(position).getPhone());
                        return convertView;
                    }

                    class MyId{
                        private TextView name;
                        private TextView phone;
                    }
                });
            }
        });
        //给item条目添加点击拨号事件。
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent it = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + list.get(position).getPhone()));
                startActivity(it);
            }
        });
    }
    //判断用户是否同意获取对应的权限。
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if( requestCode==101&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
            //进入读取联系人的方法。
            LinkMan( );
        }
    }
    //读取联系人
    private void LinkMan() {
        //通过URI获取联系人。
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        //获取内容提供者
        ContentResolver cr = getContentResolver();
        Cursor query = cr.query(uri, new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
        }, null, null, null);
        if( query!=null){
            while (query.moveToNext()) {
                String name = query.getString(query.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phone = query.getString(query.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                MyPhone myPhone = new MyPhone();
                myPhone.setName(name);
                myPhone.setPhone(phone);
                //存入数据库
                db.execSQL("insert into linkman values(?,?)",new Object[]{name,phone});
                list.add(myPhone);
                Toast.makeText(this, "name:"+name+"\tphone:"+phone, Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(this, "没有获取到联系人。", Toast.LENGTH_SHORT).show();
        }

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!