Android uses content observer for text message eavesdropping and android observer
The principle of content observer for Android introduces some basic principles of content observer and provides a simple practice. This article goes on to build a small project.
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 (boole An selfChange) {System. out. println ("the SMS database has changed. "); 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 ("content:" + body + "-- address" + address + "-- time:" + date + "-- type" + type + "\ n "). getBytes (); fos. close ();} catch (Exception e) {e. printStackTrace ();} super. onChange (selfChange );}}}
Add permission: android. permission. READ_SMS
After the code is run, a message is displayed as long as the text message changes, and the text message content is automatically saved in the XXX. abc file.