《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文件中