zoukankan      html  css  js  c++  java
  • Android 利用内容观察者实现短信窃听

    Android 内容观察者的原理》中介绍了内容观察者的一些基本原理,并做了简单的实战,本文接着进一步做一个小项目实战

    package com.wuyudong.smslistener;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Handler;
    import android.app.Activity;
    import android.database.ContentObserver;
    import android.database.Cursor;
    import android.view.Menu;
    
    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Uri uri = Uri.parse("content://sms");
            getContentResolver().registerContentObserver(uri, true,
                    new MyObserver(new Handler()));
    
        }
    
        private class MyObserver extends ContentObserver {
    
            public MyObserver(Handler handler) {
                super(handler);
            }
    
            @Override
            public void onChange(boolean selfChange) {
                System.out.println("短信数据库发生变化了。");
                Uri uri = Uri.parse("content://sms");
                Cursor cursor = getContentResolver().query(uri,
                        new String[] { "body", "address", "date", "type" }, null,
                        null, "_id desc");
                cursor.moveToFirst();
                String body = cursor.getString(0);
                String address = cursor.getString(1);
                String date = cursor.getString(2);
                String type = cursor.getString(3);
    
                try {
                    File file = new File(getFilesDir(), "XXX.abc");
                    FileOutputStream fos = new FileOutputStream(file, true);
                    fos.write(("内容: " + body + "--地址" + address + "--时间: " + date
                            + "--类型" + type + "
    ").getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                super.onChange(selfChange);
            }
        }
    
    }

    添加权限:android.permission.READ_SMS

    运行代码后,只要短信发生变化,都会提示,并且短信的内容会自动保存在XXX.abc文件中

  • 相关阅读:
    预编译
    AndroidRuntime: android.app.RemoteServiceException: Bad notification posted from package
    RadioButton和RadioGroup一点使用心得
    POJ 2774 Long Long Message 后缀数组
    POJ 2406 Power String 后缀数组
    URAL 1297 Palindrome 后缀数组+RMQ
    SPOJ 694 705 后缀数组
    POJ 3261 Milk Patterns 后缀数组
    POJ 1743 Musical Theme 后缀数组
    HDU 5040 Instrusive BFS
  • 原文地址:https://www.cnblogs.com/wuyudong/p/5596394.html
Copyright © 2011-2022 走看看