Android 接收短信

注意一点,android app无法修改短信或者删除短信,所以,查询最新短信,需要利用date字段

package com.lr.smsreaderforserver;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    Handler handler;
    LinearLayout _linerRoot;
    ScrollView _scrollview;
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        _linerRoot = (LinearLayout) this.findViewById(R.id.linerRoot);
        _scrollview= (ScrollView) this.findViewById(R.id.scrollview);
        handler = new Handler();

        //申请写的权限
        String[] permissions = {Manifest.permission.READ_SMS};
        if(PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)){
            requestPermissions(permissions,200);

        }
        else
        {
            start();
        }
    }

    void start()
    {
        getLastSmsDate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true)
                {
                    getSMS();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if( grantResults[0] ==  PackageManager.PERMISSION_GRANTED )
        {
            start();
        }
    }

    long _lastReadDate;
    void getLastSmsDate()
    {
        String SMS_URI_INBOX = "content://sms/";

        Uri uri = Uri.parse(SMS_URI_INBOX);
        String[] projection = new String[]{"date"};
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(uri, projection, null, null, "date desc");

        if(cur.moveToFirst()){

            _lastReadDate = cur.getLong(0);

            if (!cur.isClosed()) {
                cur.close();
                cur = null;
            }
        }
    }

    private  void appendLine(final String line)
    {


       handler.post(new Runnable() {
           @Override
           public void run() {
               SimpleDateFormat dateFormat = new SimpleDateFormat(
                       "yyyy-MM-dd hh:mm:ss");
               Date d = new Date();
               final String strDate = dateFormat.format(d);

               TextView textView = new TextView(MainActivity.this);
               textView.setTextSize(18);
               textView.setText(strDate + "" + line);
               _linerRoot.addView(textView);
               if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                   _scrollview.scrollToDescendant(textView);
               }

               while(_linerRoot.getChildCount() > 100)
               {
                   _linerRoot.removeViewAt(0);
               }
           }
       });
    }


    public void submitCode(final String code) {

        try {

//String urlPath = "http://192.168.1.9:80/JJKSms/RecSms.php";
            URL url = new URL("https://www.aaa.com/test?code=" + code);

            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(8000);     //设置连接超时时间
            //httpURLConnection.setDoInput(true);                  //打开输入流,以便从服务器获取数据
           //httpURLConnection.setDoOutput(true);                 //打开输出流,以便向服务器提交数据
            httpURLConnection.setRequestMethod("GET");     //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
            //设置请求体的类型是文本类型
            //httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
            //httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器写入数据
            //OutputStream outputStream = httpURLConnection.getOutputStream();
            //outputStream.write(data);

            int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
            if(response == HttpURLConnection.HTTP_OK) {
                appendLine("SetVerifyCode successfully " + code);
            }
            else
            {
                throw  new Exception("提交验证码到服务器失败,status:" + response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            appendLine(e.getMessage());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    submitCode(code);
                }
            }).start();
        }
    }

    private void getSMS() {
        final String SMS_URI_INBOX = "content://sms/";
        Pattern pattern = Pattern.compile("[0-9]{6}");

        Uri uri = Uri.parse(SMS_URI_INBOX);
        String[] projection = new String[]{"_id", "address", "person", "body", "date", "type","read"};
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(uri, projection, "date>" + _lastReadDate, null, "date desc");


        if(cur.moveToFirst()){
            int index_Address = cur.getColumnIndex("address");
            int index_Person = cur.getColumnIndex("person");
            int index_Body = cur.getColumnIndex("body");
            int index_Date = cur.getColumnIndex("date");
            int index_Type = cur.getColumnIndex("type");
            int index_id = cur.getColumnIndex("_id");
            int index_read = cur.getColumnIndex("read");
            do {
                String strAddress = cur.getString(index_Address);
                int intPerson = cur.getInt(index_Person);
                String strbody = cur.getString(index_Body);
                long longDate = cur.getLong(index_Date);
                int intType = cur.getInt(index_Type);
                int id = cur.getInt(index_id);
                int read = cur.getInt(index_read);

                if(longDate > _lastReadDate)
                    _lastReadDate = longDate;

//                SimpleDateFormat dateFormat = new SimpleDateFormat(
//                        "yyyy-MM-dd hh:mm:ss");
//                Date d = new Date(longDate);
//                String strDate = dateFormat.format(d);

                String strType = "";
                if (intType == 1) {
                    strType = "接收";
                    Log.d("SMS_Server" , "收到短信:" + strbody);

                    appendLine("收到短信:" + strbody);

                    strbody = strbody.toLowerCase();
                    if(strbody.contains("apple id"))
                    {
                        Matcher mc=pattern.matcher(strbody);
                        if(mc.find())
                        {
                            String content = mc.group();
                            appendLine("过滤出验证码:" + content);
                            submitCode(content);
                        }
                    }

                } else if (intType == 2) {
                    strType = "发送";
                } else if (intType == 3) {
                    strType = "草稿";
                } else if (intType == 4) {
                    strType = "发件箱";
                } else if (intType == 5) {
                    strType = "发送失败";
                } else if (intType == 6) {
                    strType = "待发送列表";
                } else if (intType == 0) {
                    strType = "所以短信";
                } else {
                    strType = "null";
                }

            } while (cur.moveToNext());

            if (!cur.isClosed()) {
                cur.close();
                cur = null;
            }
        }
    }

}

 

posted @ 2019-11-15 14:06  IWing  阅读(906)  评论(0编辑  收藏  举报