Androidコンテンツオブザーバー(メール盗聴)

2325 ワード

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);