欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android ContentResolver读取短信并自动填充

程序员文章站 2024-02-09 16:54:16
...

SMSContent类
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.widget.TextView;

public class SMSContent extends ContentObserver {
//上下文
private Context context;
//被填充的textView
private TextView textView;

public SMSContent(Handler handler, Context context, TextView textView) {
    super(handler);
    this.context = context;
    this.textView = textView;
}

//重写onChange方法
@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    /***
     * 查询短信的数据库并排序
     * _id id
     * address 发信人
     * body 信息内容
     */
    Cursor cursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"),
            new String[]{"_id", "address", "body"},
            null, null, "_id desc");
    if (cursor != null && cursor.getCount() > 0) {
        //获得第一条短信的信息
        cursor.moveToFirst();
        String body = cursor.getString(cursor.getColumnIndex("body"));
        //设置给textView
        textView.setText(body);
    }
}

}

MainActivity类
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //初始化控件
    textView = findViewById(R.id.textView);
    //获取权限
    getAccess(Manifest.permission.READ_SMS);
    //注册监听
    SMSContent smsContent = new SMSContent(new Handler(), this, textView);
    this.getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, smsContent);
}

private void getAccess(String permission) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        return;
    if (ContextCompat.checkSelfPermission(getApplication(), permission) == PackageManager.PERMISSION_GRANTED)
        return;
    ActivityCompat.requestPermissions(this, new String[]{permission}, 1);
}

}