监听短信
- - CSDN博客推荐文章在监听短信在这个功能中,通知观察者的工作已经有别人做好,我们只需要注册一个观察者即可. System.out.println( new Date(date)+" 您收到 " + address +"给你发的一封短信,短信内容为: \n" +body );. 最后千万别忘了在清单文件上加上所需要的相应权限.
在监听短信在这个功能中,通知观察者的工作已经有别人做好,我们只需要注册一个观察者即可。。。。
1、原理图:
2、MainActivity
package com.njupt.smsobserver2; import java.util.Date; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.ContentResolver; import android.database.ContentObserver; import android.database.Cursor; import android.view.Menu; public class MainActivity extends Activity { private Uri uri; private ContentResolver resolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); uri = Uri.parse("content://sms"); resolver = getContentResolver(); resolver.registerContentObserver(uri,true,new SmsObserver2()); } private class SmsObserver2 extends ContentObserver{ public SmsObserver2(){ super(new Handler()); } @Override public void onChange(boolean selfChange) { Cursor c = resolver.query(uri, null, null, null, "_id DESC LIMIT 1"); while(c.moveToNext()){ String address = c.getString(c.getColumnIndex("address")); String body = c.getString(c.getColumnIndex("body")); long date = c.getLong(c.getColumnIndex("date")); int type = c.getInt(c.getColumnIndex("type")); if(type == 1){ System.out.println( new Date(date)+" 您收到 " + address +"给你发的一封短信,短信内容为: \n" +body ); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
最后千万别忘了在清单文件上加上所需要的相应权限
<uses-permission android:name="android.permission.READ_SMS"/> <uses-permission android:name="android.permission.WRITE_SMS"/>