Android 監聽簡訊資料庫過濾獲取簡訊內容上傳至伺服器

来源:https://www.cnblogs.com/yelanggu/archive/2023/02/15/17124273.html
-Advertisement-
Play Games

本文翻譯自: Composition in Flutter & Dart 在 Flutter & Dart 中使用組合創建模塊化應用程式。 什麼是組合? 在dictionary.com 中 composition 的定義為:將部分或者元素組合成一個整體的行為。簡單說,組合就像堆樂高積木,我們可以將積 ...


前言

Android 監聽簡訊的方式有兩種

1、監聽簡訊資料庫,資料庫發生改變時回調。

2、監聽簡訊廣播

其中第二種方式由於國內各廠家的定製Android 可能導致無響應 目前測試 魅族 無法監聽到簡訊廣播

本文介紹第一種方式監聽簡訊

一、創建Service前臺服務

package com.iwhalecloud.demo.SMS;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.RequiresApi;
import com.iwhalecloud.demo.MainActivity;
import com.iwhalecloud.demo.R;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyService extends Service {
	private static final String TAG = MyService.class.getSimpleName();
    private SMSContentObserver smsObserver;
    public String phoneNo = "";
    public String httpUrl = "";

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    public class MyBinder extends Binder {
        /**
         * 獲取當前Service的實例
         * @return
         */
        public MyService getService(){
            return MyService.this;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        //註冊觀察者
        smsObserver = new SMSContentObserver(MyService.this,new Handler());
        getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, smsObserver);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        phoneNo=intent.getStringExtra("phoneNum");
        httpUrl=intent.getStringExtra("httpUrl");
        startForeground(100,getNotification("服務運行中...","正在監聽號碼:"+phoneNo+",保持應用後臺運行..."));
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(smsObserver);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private Notification getNotification(String title, String message){
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 唯一的通知通道的id.
        String notificationChannelId = "notification_channel_id_01";
        // Android8.0以上的系統,新建消息通道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //用戶可見的通道名稱
            String channelName = "Foreground Service Notification";
            //通道的重要程度
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
            notificationChannel.setDescription("Channel description");
            //LED燈
            notificationChannel.enableLights(false);
            //震動
            notificationChannel.enableVibration(false);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(notificationChannel);
            }
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
        //通知小圖標
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //通知標題
        builder.setContentTitle(title);
        //通知內容
        builder.setContentText(message);
        //設定通知顯示的時間
        builder.setWhen(System.currentTimeMillis());
        //設定啟動的內容
        Intent clickIntent = new Intent(Intent.ACTION_MAIN);
        //點擊回到活動主頁 而不是創建新主頁
        clickIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        clickIntent.setComponent(new ComponentName(this,MainActivity.class));
        clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        //創建通知並返回
        return builder.build();
    }
    @SuppressLint("Range")
    private  void setSmsCode() {
        Toast.makeText(MyService.this,phoneNo+":"+httpUrl,Toast.LENGTH_SHORT).show();
        Cursor cursor = null;
        // 添加異常捕捉
        try {
            cursor = getContentResolver().query(
                    Uri.parse("content://sms"),
                    new String[] { "_id", "address", "body", "date" },
                    null, null, "date desc"); //
            if (cursor != null) {
                cursor.moveToFirst();
                final long smsdate = Long.parseLong(cursor.getString(cursor.getColumnIndex("date")));
                final long nowdate = System.currentTimeMillis();
                Toast.makeText(MyService.this,nowdate+":"+smsdate+"===="+ (nowdate - smsdate),Toast.LENGTH_SHORT).show();
//                 如果當前時間和簡訊時間間隔超過60秒,認為這條簡訊無效
                final String strAddress = cursor.getString(cursor.getColumnIndex("address"));    // 簡訊號碼
                final String strBody = cursor.getString(cursor.getColumnIndex("body"));          // 在這裡獲取簡訊信息
                Toast.makeText(MyService.this,"strAddress:"+strAddress,Toast.LENGTH_SHORT).show();
                Toast.makeText(MyService.this,"strBody:"+strBody,Toast.LENGTH_SHORT).show();
                if (nowdate - smsdate > 60 * 1000) {
                    Log.i(TAG, "簡訊過期");
                    Toast.makeText(MyService.this,"簡訊過期",Toast.LENGTH_SHORT).show();
                    return;
                }

                final int smsid = cursor.getInt(cursor.getColumnIndex("_id"));
                if (TextUtils.isEmpty(strAddress) || TextUtils.isEmpty(strBody)) {
                    return;
                }
                Log.i(TAG, "phoneNo: "+phoneNo);
                Log.i(TAG, "httpUrl: "+httpUrl);
                if (strAddress.equals(phoneNo)){
                    Log.i(TAG, "是我想要的號碼");
                    Toast.makeText(MyService.this,strAddress+":"+strBody,Toast.LENGTH_SHORT).show();
                    Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{6})(?![0-9])");
                    Matcher m = continuousNumberPattern.matcher(strBody);
                    String dynamicPassword = "";
                    while (m.find()) {
                        dynamicPassword = m.group();
                    }
                    //連接http服務
                    String finalDynamicPassword = dynamicPassword;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            OkHttpClient mOkHttpClient = new OkHttpClient();
                            try {
                                RequestBody requestBody = new FormBody.Builder().add("code", finalDynamicPassword).build();
                                Request request = new Request.Builder().url(httpUrl).post(requestBody).build();
                                Response response = mOkHttpClient.newCall(request).execute();//發送請求
                                String result = response.body().string();
                                Log.d(TAG, "result: " + result);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    Log.i(TAG, "onReceiveSms: "+ dynamicPassword);
                }
            }else {
                Toast.makeText(MyService.this,"cursor 為 NULL",Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e) {
            Toast.makeText(MyService.this,"出錯了::::"+e.getMessage(),Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        finally {
            Toast.makeText(MyService.this, String.valueOf(cursor != null),Toast.LENGTH_SHORT).show();
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    public class SMSContentObserver extends ContentObserver {
        private static final int MSG = 1;
        private int flag = 0;
        private Context mContext;
        private Handler mHandler;
        public SMSContentObserver(Context mContext,
                                  Handler mHandler) {
            super(mHandler);
            this.mContext = mContext;
            this.mHandler = mHandler;
        }
        @Override
        public void onChange(boolean selfChange) {
            // TODO Auto-generated method stub
            super.onChange(selfChange);
            //onchange調用兩次  過濾掉一次
            if (flag%2 == 1){
                setSmsCode();
            }
            flag++;
        }
    }
    
}

二、主界面(參考)

package com.iwhalecloud.demo;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;
import com.iwhalecloud.demo.SMS.MyService;

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "CC";
    final private int REQUEST_CODE_ASK_PERMISSIONS = 1;
    private boolean serviceFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences read = getSharedPreferences("info", MODE_PRIVATE);
        String phoneNum = "10659874";
        String httpUrl= "";
        if (read.getString("phoneNum",null)!=null){
            phoneNum = read.getString("phoneNum",null);
        }
        if (read.getString("httpUrl",null)!=null){
            httpUrl = read.getString("httpUrl",null);
        }
        TextView v1 = findViewById(R.id.editText1);
        TextView v2 = findViewById(R.id.editText2);
        v1.setText(phoneNum);
        v2.setText(httpUrl);
        ToggleButton tb = findViewById(R.id.button);
        tb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView pn = findViewById(R.id.editText1);
                TextView httpUrl = findViewById(R.id.editText2);
                if (tb.isChecked()){
                    Intent service = new Intent(getApplicationContext(), MyService.class);
                    SharedPreferences.Editor editor = getSharedPreferences("info",MODE_PRIVATE).edit();
                    editor.putString("phoneNum",pn.getText().toString());
                    editor.putString("httpUrl",httpUrl.getText().toString());
                    editor.apply();
                    service.putExtra("phoneNum",pn.getText().toString());
                    service.putExtra("httpUrl",httpUrl.getText().toString
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ###2.1 布爾值 布爾數據類型只有兩種:True和False,要註意大小寫。 類真與類假:其它數據類型中的一些值,條件會認為它們等價於True和False,例如:0、0.0 和 ' '(空字元串)會被認為是False,其它值被認為是True。 布爾數據類型可以用於表達式,並且可以保存到變數中,但 ...
  • Linux 配置vim/**********************************************/Vim 是最重要的編輯器之一,主要有下麵幾個優點。1.可以不使用滑鼠,完全用鍵盤操作。2.系統資源占用小,打開大文件毫無壓力。3.鍵盤命令變成肌肉記憶以後,操作速度極快。4.伺服器默 ...
  • 開發的軟體安裝後,windows上提示病毒,默默被系統刪除了。 一開始以為是自己軟體的簽名問題,後面發現,將被隔離的文件還原,文件的簽名是存在的。 這是微軟denfender的誤報,為啥會報病毒呢? emmm,這個Entry.exe是作為應用版本的啟動入口。 啟動了太多的應用,就被安全中心識別成流氓 ...
  • 閱識風雲是華為雲信息大咖,擅長將複雜信息多元化呈現,其出品的一張圖(雲圖說)、深入淺出的博文(雲小課)或短視頻(雲視廳)總有一款能讓您快速上手華為雲。更多精彩內容請單擊此處。 摘要:當HDFS集群出現DataNode節點間磁碟利用率不平衡時,會導致MapReduce應用程式無法很好地利用本地計算的優 ...
  • pdf下載:密碼7281 專欄目錄首頁:【專欄必讀】(考研覆試)資料庫系統概論第五版(王珊)專欄學習筆記目錄導航及課後習題答案詳解 SQL數據更新主要有三種形式 插入數據(INSERT) 修改數據(UPDATE) 刪除數據(DELETE) 一:插入數據(INSERT) (1)插入元組 語法:格式如下 ...
  • 1.創建物化視圖 alter session set container=pdb; grant create materialized view to scott; create materialized view 物化視圖名 -- 1. 創建物化視圖build [immediate | defer ...
  • 摘要:本篇文檔為使用GDS導入示例的具體簡單步驟和示例。 本文分享自華為雲社區《帶你快速入門GDS導入導出,玩轉PB級數倉GaussDB(DWS)》,作者: yd_220527686。 1、創建導入目標表 CREATE TABLE tpcds_reasons ( r_reason_sk intege ...
  • GreatSQL社區原創內容未經授權不得隨意使用,轉載請聯繫小編並註明來源。 GreatSQL是MySQL的國產分支版本,使用上與MySQL一致。 作者: 花家舍 文章來源:GreatSQL社區原創 前文回顧 實現一個簡單的Database系列 譯註:cstack在github維護了一個簡單的、類似 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...