Android内容观察者(短信窃听)

package com.example.smswatcher;

import com.pas.model.SmsInfo;

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.text.Layout;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{

	LinearLayout layout; 
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		layout=(LinearLayout)findViewById(R.id.ll);
		ContentResolver resolver = getContentResolver();
		Uri uri = Uri.parse("content://sms/");

		//注册观察者
		resolver.registerContentObserver(uri, true, new MyObserver(new Handler()));
	}

	private class MyObserver extends ContentObserver
	{

		public MyObserver(Handler handler)
		{
			super(handler);
		}

		// 内容观察者观察到内容变化调用
		// 观察到消息邮箱有一条数据库内容变化的通知
		@Override
		public void onChange(boolean selfChange)
		{
			super.onChange(selfChange);
			SmsInfo sms=getLastSms();
			TextView tv=new TextView(MainActivity.this);
			tv.setText(sms.toString());
//			Toast.makeText(MainActivity.this, sms.toString(), Toast.LENGTH_LONG).show();
			layout.addView(tv);
		}

	}

	@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;
	}

	private SmsInfo getLastSms()
	{
		Uri uri = Uri.parse("content://sms/");
		ContentResolver resolver = getContentResolver();
		Cursor cursor = resolver.query(uri, new String[]
		{ "address", "date", "type", "body" }, null, null, null);
		cursor.moveToFirst();
		String address = cursor.getString(0);
		String date = cursor.getString(1);
		String type = cursor.getString(2);
		String body = cursor.getString(3);
		cursor.close();
		return new SmsInfo(address, type, date, body);
	}

}


如果想在自定义的逻辑里面添加通知,使用:

		context.getContentResolver()
		.notifyChange(Uri.parse("content://com.pas.sqlite.personprovider"), null);

 

你可能感兴趣的:(Android内容观察者(短信窃听))