android 短信通知和SQLITE 应用

 

最近有需求做个一手机开机后,监听手机短信(指定短信内容)通知客户。下面将实现代码写出来

短信通知广播拦截BootReceiver

 

Java代码 复制代码  收藏代码
  1. package com.msi.manning;   
  2.   
  3. import java.util.ArrayList;   
  4.   
  5. import android.app.NotificationManager;   
  6. import android.content.BroadcastReceiver;   
  7. import android.content.Context;   
  8. import android.content.Intent;   
  9. import android.os.Bundle;   
  10. import android.telephony.gsm.SmsMessage;   
  11. import android.util.Log;   
  12.   
  13. /**  
  14.  * 2011-4-18 下午01:43:17 BootReceiver.java author:zhouhui  
  15.  * E-mail:wwwzhouhui@163.com  
  16.  */  
  17. public class BootReceiver extends BroadcastReceiver {   
  18.     static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";   
  19.     private static final String LOG_TAG = "SMSReceiver";   
  20.     public static final int NOTIFICATION_ID_RECEIVED = 0x1221;   
  21.   
  22.     @Override  
  23.     public void onReceive(Context context, Intent intent) {   
  24.         NotificationManager nm = (NotificationManager) context   
  25.                 .getSystemService(Context.NOTIFICATION_SERVICE);   
  26.         ArrayList<String> list = new ArrayList<String>();   
  27.         if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {   
  28.             // Intent in = new Intent(context, SMSNotifyActivity.class); //   
  29.             // 这是你的activity   
  30.             // in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
  31.             // context.startActivity(in);   
  32.         }   
  33.         if (intent.getAction().equals(BootReceiver.ACTION)) {   
  34.             Bundle bundle = intent.getExtras();   
  35.             StringBuilder sb = new StringBuilder();   
  36.             if (bundle != null) {   
  37.                 Object messages[] = (Object[]) bundle.get("pdus");   
  38.                 SmsMessage[] smsMessage = new SmsMessage[messages.length];   
  39.   
  40.                 for (int n = 0; n < messages.length; n++) {   
  41.                     smsMessage[n] = SmsMessage   
  42.                             .createFromPdu((byte[]) messages[n]);   
  43.                     sb.append("From:");   
  44.                     sb.append(smsMessage[n].getDisplayOriginatingAddress());   
  45.                     sb.append("\n");   
  46.                     sb.append(smsMessage[n].getDisplayMessageBody());   
  47.                     list.add(sb.toString());   
  48.                 }   
  49.             }   
  50.             Log.i(BootReceiver.LOG_TAG, "[SMSApp] onReceiveIntent0: " + sb);   
  51.             abortBroadcast();   
  52.   
  53.             Intent in = new Intent(context, SMSNotifyActivity.class);   
  54.             Bundle bundle2 = new Bundle();   
  55.             bundle2.putStringArrayList("message", list);   
  56.             in.putExtras(bundle2);   
  57.             in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
  58.             context.startActivity(in);   
  59.             Log.i(BootReceiver.LOG_TAG, "[SMSApp] onReceiveIntent0over: " );   
  60.         }   
  61.     }   
  62.   
  63. }  
package com.msi.manning;

import java.util.ArrayList;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.util.Log;

/**
 * 2011-4-18 下午01:43:17 BootReceiver.java author:zhouhui
 * E-mail:wwwzhouhui@163.com
 */
public class BootReceiver extends BroadcastReceiver {
	static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private static final String LOG_TAG = "SMSReceiver";
	public static final int NOTIFICATION_ID_RECEIVED = 0x1221;

	@Override
	public void onReceive(Context context, Intent intent) {
		NotificationManager nm = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		ArrayList<String> list = new ArrayList<String>();
		if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
			// Intent in = new Intent(context, SMSNotifyActivity.class); //
			// 这是你的activity
			// in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			// context.startActivity(in);
		}
		if (intent.getAction().equals(BootReceiver.ACTION)) {
			Bundle bundle = intent.getExtras();
			StringBuilder sb = new StringBuilder();
			if (bundle != null) {
				Object messages[] = (Object[]) bundle.get("pdus");
				SmsMessage[] smsMessage = new SmsMessage[messages.length];

				for (int n = 0; n < messages.length; n++) {
					smsMessage[n] = SmsMessage
							.createFromPdu((byte[]) messages[n]);
					sb.append("From:");
					sb.append(smsMessage[n].getDisplayOriginatingAddress());
					sb.append("\n");
					sb.append(smsMessage[n].getDisplayMessageBody());
					list.add(sb.toString());
				}
			}
			Log.i(BootReceiver.LOG_TAG, "[SMSApp] onReceiveIntent0: " + sb);
			abortBroadcast();

			Intent in = new Intent(context, SMSNotifyActivity.class);
			Bundle bundle2 = new Bundle();
			bundle2.putStringArrayList("message", list);
			in.putExtras(bundle2);
			in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(in);
			Log.i(BootReceiver.LOG_TAG, "[SMSApp] onReceiveIntent0over: " );
		}
	}

}

 

    手机发送短信广播后会给android.provider.Telephony.SMS_RECEIVED 拦截 取得短信内容后面通知需要显示拦截展现的Activity

   显示短信拦截内容的SMSNotifyActivity 

   package com.msi.manning;

Java代码 复制代码  收藏代码
  1. import java.util.ArrayList;   
  2. import java.util.HashMap;   
  3.   
  4. import android.app.Activity;   
  5. import android.database.Cursor;   
  6. import android.os.Bundle;   
  7. import android.util.Log;   
  8. import android.view.View;   
  9. import android.view.View.OnClickListener;   
  10. import android.widget.Button;   
  11. import android.widget.ListView;   
  12.   
  13. public class SMSNotifyActivity extends Activity {   
  14.     private static final String LOG_TAG = "SMSReceiver";   
  15.     Button closeBtn;   
  16.     Button clearBtn;   
  17.     Button deleteBtn;   
  18.     ListView list;   
  19.     ListViewButtonAdapter listItemAdapter;   
  20.     private DiaryDbAdapter mDbHelper;   
  21.     private Cursor mDiaryCursor;   
  22.   
  23.     public void onCreate(Bundle icicle) {   
  24.         super.onCreate(icicle);   
  25.         setContentView(R.layout.main);   
  26.         initLayout();   
  27.     }   
  28.   
  29.     /**  
  30.      * 查詢最新全部短信通知數據  
  31.      */  
  32.     private void renderListView() {   
  33.         mDiaryCursor = mDbHelper.getAllMessage();   
  34.         ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();   
  35.         mDiaryCursor.moveToFirst();   
  36.         while (!mDiaryCursor.isAfterLast()) {   
  37.             HashMap<String, Object> map = new HashMap<String, Object>();   
  38.             String status = mDiaryCursor.getString(5);   
  39.             if (status.equals("0")) {   
  40.                 status = "未查看";   
  41.             } else {   
  42.                 status = "已查看";   
  43.             }   
  44.             map.put("ItemTitle", mDiaryCursor.getLong(0));   
  45.             map.put("ItemType", mDiaryCursor.getString(3));   
  46.             map.put("ItemTime", mDiaryCursor.getString(4));   
  47.             map.put("ItemStatus", status);   
  48.             map.put("ItemText", mDiaryCursor.getString(1));   
  49.             listItem.add(map);   
  50.             mDiaryCursor.moveToNext();   
  51.         }   
  52.         mDiaryCursor.close();   
  53.         // 生成适配器的Item和动态数组对应的元素   
  54.         listItemAdapter = new ListViewButtonAdapter(this, listItem,// 数据源   
  55.                 R.layout.list,// ListItem的XML实现   
  56.                 // 动态数组与ImageItem对应的子项   
  57.                 new String[] { "ItemTitle""ItemType""ItemTime",   
  58.                         "ItemStatus""ItemText""ItemTitle""ItemTitle" },   
  59.                 // ImageItem的XML文件里面的一个ImageView,两个TextView ID   
  60.                 new int[] { R.id.ItemTitle, R.id.ItemType, R.id.ItemTime,   
  61.                         R.id.ItemStatus, R.id.ItemText, R.id.btn_config_delete,   
  62.                         R.id.btn_config_view }, mDbHelper);   
  63.         // 添加并且显示   
  64.         list.setAdapter(listItemAdapter);   
  65.     }   
  66.   
  67.     /**  
  68.      * 初始化組件  
  69.      */  
  70.     private void initLayout() {   
  71.         // 绑定Layout里面的ListView   
  72.         list = (ListView) findViewById(R.id.MyListView);   
  73.         this.closeBtn = (Button) findViewById(R.id.btn_config_close);   
  74.         this.clearBtn = (Button) findViewById(R.id.btn_config_clear);   
  75.         closeBtn.setOnClickListener(new closeBtn_Click());   
  76.         clearBtn.setOnClickListener(new clearBtn_Click());   
  77.     }   
  78.   
  79.     @Override  
  80.     protected void onStart() {   
  81.         super.onStart();   
  82.         mDbHelper = new DiaryDbAdapter(this);   
  83.         mDbHelper.open();   
  84.         Bundle extras = getIntent().getExtras();   
  85.         ArrayList<String> data = null;   
  86.         if (extras != null) {   
  87.             data = extras.getStringArrayList("message");   
  88.             for (int j = 0; j < data.size(); j++) {   
  89.                 String[] array = data.get(j).split("\n");   
  90.                 String[] message = array[1].split("#");   
  91.                 mDbHelper.createDiary(message[4], message[1], message[2], "0",   
  92.                         message[3]);   
  93.             }   
  94.         }   
  95.         Log.i(SMSNotifyActivity.LOG_TAG, "[SMSApp] onReceiveIntent1: " + data);   
  96.         renderListView();   
  97.     }   
  98.   
  99.     /**  
  100.      * 關閉短信通知  
  101.      *   
  102.      * @author dell  
  103.      *   
  104.      */  
  105.     public class closeBtn_Click implements OnClickListener {   
  106.         public void onClick(View arg0) {   
  107.             SMSNotifyActivity.this.finish();   
  108.         }   
  109.     }   
  110.   
  111.     /**  
  112.      * 清除所有短信通知  
  113.      *   
  114.      * @author dell  
  115.      *   
  116.      */  
  117.     public class clearBtn_Click implements OnClickListener {   
  118.         public void onClick(View arg0) {   
  119.             boolean flag = mDbHelper.deleteAll();   
  120.             Log.i(SMSNotifyActivity.LOG_TAG, "[SMSApp] clearBtn_Click: " + flag);   
  121.             listItemAdapter.notifyDataSetChanged();   
  122.             // 刷新頁面   
  123.             renderListView();   
  124.         }   
  125.     }   
  126.   
  127.     protected void onRestart() {   
  128.         super.onRestart();   
  129.         Log.e(LOG_TAG, "start onRestart~~~");   
  130.     }   
  131.   
  132.     @Override  
  133.     protected void onResume() {   
  134.         super.onResume();   
  135.         Log.e(LOG_TAG, "start onResume~~~");   
  136.     }   
  137.   
  138.     @Override  
  139.     protected void onPause() {   
  140.         super.onPause();   
  141.         Log.e(LOG_TAG, "start onPause~~~");   
  142.     }   
  143.   
  144.     @Override  
  145.     protected void onStop() {   
  146.         super.onStop();   
  147.         Log.e(LOG_TAG, "start onStop~~~");   
  148.     }   
  149.   
  150.     @Override  
  151.     protected void onDestroy() {   
  152.         super.onDestroy();   
  153.         Log.e(LOG_TAG, "start onDestroy~~~");   
  154.     }   
  155. }  
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class SMSNotifyActivity extends Activity {
	private static final String LOG_TAG = "SMSReceiver";
	Button closeBtn;
	Button clearBtn;
	Button deleteBtn;
	ListView list;
	ListViewButtonAdapter listItemAdapter;
	private DiaryDbAdapter mDbHelper;
	private Cursor mDiaryCursor;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		initLayout();
	}

	/**
	 * 查詢最新全部短信通知數據
	 */
	private void renderListView() {
		mDiaryCursor = mDbHelper.getAllMessage();
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
		mDiaryCursor.moveToFirst();
		while (!mDiaryCursor.isAfterLast()) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			String status = mDiaryCursor.getString(5);
			if (status.equals("0")) {
				status = "未查看";
			} else {
				status = "已查看";
			}
			map.put("ItemTitle", mDiaryCursor.getLong(0));
			map.put("ItemType", mDiaryCursor.getString(3));
			map.put("ItemTime", mDiaryCursor.getString(4));
			map.put("ItemStatus", status);
			map.put("ItemText", mDiaryCursor.getString(1));
			listItem.add(map);
			mDiaryCursor.moveToNext();
		}
		mDiaryCursor.close();
		// 生成适配器的Item和动态数组对应的元素
		listItemAdapter = new ListViewButtonAdapter(this, listItem,// 数据源
				R.layout.list,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemTitle", "ItemType", "ItemTime",
						"ItemStatus", "ItemText", "ItemTitle", "ItemTitle" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemTitle, R.id.ItemType, R.id.ItemTime,
						R.id.ItemStatus, R.id.ItemText, R.id.btn_config_delete,
						R.id.btn_config_view }, mDbHelper);
		// 添加并且显示
		list.setAdapter(listItemAdapter);
	}

	/**
	 * 初始化組件
	 */
	private void initLayout() {
		// 绑定Layout里面的ListView
		list = (ListView) findViewById(R.id.MyListView);
		this.closeBtn = (Button) findViewById(R.id.btn_config_close);
		this.clearBtn = (Button) findViewById(R.id.btn_config_clear);
		closeBtn.setOnClickListener(new closeBtn_Click());
		clearBtn.setOnClickListener(new clearBtn_Click());
	}

	@Override
	protected void onStart() {
		super.onStart();
		mDbHelper = new DiaryDbAdapter(this);
		mDbHelper.open();
		Bundle extras = getIntent().getExtras();
		ArrayList<String> data = null;
		if (extras != null) {
			data = extras.getStringArrayList("message");
			for (int j = 0; j < data.size(); j++) {
				String[] array = data.get(j).split("\n");
				String[] message = array[1].split("#");
				mDbHelper.createDiary(message[4], message[1], message[2], "0",
						message[3]);
			}
		}
		Log.i(SMSNotifyActivity.LOG_TAG, "[SMSApp] onReceiveIntent1: " + data);
		renderListView();
	}

	/**
	 * 關閉短信通知
	 * 
	 * @author dell
	 * 
	 */
	public class closeBtn_Click implements OnClickListener {
		public void onClick(View arg0) {
			SMSNotifyActivity.this.finish();
		}
	}

	/**
	 * 清除所有短信通知
	 * 
	 * @author dell
	 * 
	 */
	public class clearBtn_Click implements OnClickListener {
		public void onClick(View arg0) {
			boolean flag = mDbHelper.deleteAll();
			Log.i(SMSNotifyActivity.LOG_TAG, "[SMSApp] clearBtn_Click: " + flag);
			listItemAdapter.notifyDataSetChanged();
			// 刷新頁面
			renderListView();
		}
	}

	protected void onRestart() {
		super.onRestart();
		Log.e(LOG_TAG, "start onRestart~~~");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.e(LOG_TAG, "start onResume~~~");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.e(LOG_TAG, "start onPause~~~");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.e(LOG_TAG, "start onStop~~~");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.e(LOG_TAG, "start onDestroy~~~");
	}
}

    短信拦截后的记录插入到数据库中,这里有个SQLlite辅助类DiaryDbAdapter

    package com.msi.manning;

Java代码 复制代码  收藏代码
  1. import java.util.Calendar;   
  2.   
  3. import android.content.ContentValues;   
  4. import android.content.Context;   
  5. import android.database.Cursor;   
  6. import android.database.SQLException;   
  7. import android.database.sqlite.SQLiteDatabase;   
  8. import android.database.sqlite.SQLiteOpenHelper;   
  9. import android.util.Log;   
  10.   
  11. public class DiaryDbAdapter {   
  12.   
  13.     private static final String PUSH_ID = "push_id"//邮件等类型的主键   
  14.     private static final String CONTENT = "content"//邮件等类型的简略内容   
  15.     private static final String SMS_FUNC_CODE = "sms_func_code"//通知类型代码   
  16.     private static final String SMS_FUNC_CODE_CN = "sms_func_code_cn"//通知类型中文名   
  17.     private static final String CREATE_TIME = "create_time"//该记录创建的时间   
  18.     private static final String STATUS = "status";  //通知状态   
  19.     private static final String REQID = "reqid";  //通知状态   
  20.     private static final String DATABASE_NAME = "dbForMessage";   
  21.     private static final String DATABASE_TABLE = "iuc_push_record";   
  22.     private static final int DATABASE_VERSION = 1;   
  23.   
  24.     private static final String TAG = "DiaryDbAdapter";   
  25.     private DatabaseHelper mDbHelper;   
  26.     private SQLiteDatabase mDb;   
  27.   
  28.     private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE + " (" + PUSH_ID   
  29.         + " INTEGER PRIMARY KEY autoincrement, " + CONTENT + " text not null, " +SMS_FUNC_CODE + " text," + SMS_FUNC_CODE_CN + " text," +CREATE_TIME + " text," +STATUS + " text, "+REQID + " text "");";   
  30. //  private static final String DATABASE_CREATE = "create table diary (_id integer primary key autoincrement, "   
  31. //      + "title text not null, body text not null, created text not null);";   
  32.   
  33.     private final Context mCtx;   
  34.   
  35.     private static class DatabaseHelper extends SQLiteOpenHelper {   
  36.   
  37.         DatabaseHelper(Context context) {   
  38.             super(context, DATABASE_NAME, null, DATABASE_VERSION);   
  39.         }   
  40.   
  41.         @Override  
  42.         public void onCreate(SQLiteDatabase db) {   
  43.             Log.i(TAG, "[SMSApp] createDatabase: " +DATABASE_CREATE);   
  44.             db.execSQL(DATABASE_CREATE);   
  45.         }   
  46.   
  47.         @Override  
  48.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {   
  49.             Log.i(TAG, "[SMSApp] updatgeDatabase: " +DATABASE_CREATE);   
  50.             db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);   
  51.             onCreate(db);   
  52.         }   
  53.     }   
  54.   
  55.     public DiaryDbAdapter(Context ctx) {   
  56.         this.mCtx = ctx;   
  57.     }   
  58.   
  59.     public DiaryDbAdapter open() throws SQLException {   
  60.         mDbHelper = new DatabaseHelper(mCtx);   
  61.         mDb = mDbHelper.getWritableDatabase();   
  62.         return this;   
  63.     }   
  64.   
  65.     public void closeclose() {   
  66.         mDbHelper.close();   
  67.     }   
  68.   
  69.     public long createDiary(String content, String sms_func_code,String sms_func_code_cn,String status,String reqid) {   
  70.         ContentValues initialValues = new ContentValues();   
  71.         initialValues.put(CONTENT, content);   
  72.         initialValues.put(SMS_FUNC_CODE, sms_func_code);   
  73.         initialValues.put(SMS_FUNC_CODE_CN, sms_func_code_cn);   
  74.         initialValues.put(STATUS, status);   
  75.         initialValues.put(REQID, reqid);   
  76.         Calendar calendar = Calendar.getInstance();   
  77.         String created = calendar.get(Calendar.YEAR) + "年"  
  78.                 + calendar.get(Calendar.MONTH) + "月"  
  79.                 + calendar.get(Calendar.DAY_OF_MONTH) + "日"  
  80.                 + calendar.get(Calendar.HOUR_OF_DAY) + "时"  
  81.                 + calendar.get(Calendar.MINUTE) + "分";   
  82.         initialValues.put(CREATE_TIME, created);   
  83.         Log.i(TAG, "[SMSApp] insertsql: ");   
  84.         return mDb.insert(DATABASE_TABLE, null, initialValues);   
  85.     }   
  86.   
  87.     public boolean deleteDiary(long rowId) {   
  88.         Log.i(TAG, "[SMSApp] deletesql: "+rowId);   
  89.         return mDb.delete(DATABASE_TABLE, PUSH_ID + "=" + rowId, null) > 0;   
  90.     }   
  91.        
  92.     public boolean deleteAll() {   
  93.         Log.i(TAG, "[SMSApp] deleteallsql: ");   
  94.         return mDb.delete(DATABASE_TABLE, nullnull) > 0;   
  95.            
  96.     }   
  97.   
  98.     public Cursor getAllMessage() {   
  99.         Log.i(TAG, "[SMSApp] getallsql: ");   
  100.         return mDb.query(DATABASE_TABLE, new String[] { PUSH_ID, CONTENT,   
  101.                 SMS_FUNC_CODE, SMS_FUNC_CODE_CN,CREATE_TIME,STATUS,REQID }, nullnullnullnullnull);   
  102.     }   
  103.   
  104.     public Cursor getDiary(long rowId) throws SQLException {   
  105.   
  106.         Cursor mCursor =   
  107.   
  108.         mDb.query(true, DATABASE_TABLE, new String[] { PUSH_ID, CONTENT,   
  109.                 SMS_FUNC_CODE, SMS_FUNC_CODE_CN,CREATE_TIME,STATUS,REQID }, PUSH_ID + "=" + rowId, nullnull,   
  110.                 nullnullnull);   
  111.         Log.i(TAG, "[SMSApp] getDiarysql: ");   
  112.         if (mCursor != null) {   
  113.             mCursor.moveToFirst();   
  114.         }   
  115.         return mCursor;   
  116.   
  117.     }   
  118.   
  119.     public boolean updateDiary(long rowId, String content, String sms_func_code,String sms_func_code_cn,String status,String reqid) {   
  120.         ContentValues args = new ContentValues();   
  121.         args.put(CONTENT, content);   
  122.         args.put(SMS_FUNC_CODE, sms_func_code);   
  123.         args.put(SMS_FUNC_CODE_CN, sms_func_code_cn);   
  124.         args.put(STATUS, status);   
  125.         args.put(REQID, reqid);   
  126.         Calendar calendar = Calendar.getInstance();   
  127.         String created = calendar.get(Calendar.YEAR) + "年"  
  128.                 + calendar.get(Calendar.MONTH) + "月"  
  129.                 + calendar.get(Calendar.DAY_OF_MONTH) + "日"  
  130.                 + calendar.get(Calendar.HOUR_OF_DAY) + "时"  
  131.                 + calendar.get(Calendar.MINUTE) + "分";   
  132.         args.put(CREATE_TIME, created);   
  133.         Log.i(TAG, "[SMSApp] updatesql: ");   
  134.         return mDb.update(DATABASE_TABLE, args, PUSH_ID + "=" + rowId, null) > 0;   
  135.     }   
  136. }  
import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DiaryDbAdapter {

	private static final String PUSH_ID = "push_id"; //邮件等类型的主键
	private static final String CONTENT = "content"; //邮件等类型的简略内容
	private static final String SMS_FUNC_CODE = "sms_func_code"; //通知类型代码
	private static final String SMS_FUNC_CODE_CN = "sms_func_code_cn"; //通知类型中文名
	private static final String CREATE_TIME = "create_time"; //该记录创建的时间
	private static final String STATUS = "status";  //通知状态
	private static final String REQID = "reqid";  //通知状态
	private static final String DATABASE_NAME = "dbForMessage";
	private static final String DATABASE_TABLE = "iuc_push_record";
	private static final int DATABASE_VERSION = 1;

	private static final String TAG = "DiaryDbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE + " (" + PUSH_ID
		+ " INTEGER PRIMARY KEY autoincrement, " + CONTENT + " text not null, " +SMS_FUNC_CODE + " text," + SMS_FUNC_CODE_CN + " text," +CREATE_TIME + " text," +STATUS + " text, "+REQID + " text "+ ");";
//	private static final String DATABASE_CREATE = "create table diary (_id integer primary key autoincrement, "
//		+ "title text not null, body text not null, created text not null);";

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.i(TAG, "[SMSApp] createDatabase: " +DATABASE_CREATE);
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.i(TAG, "[SMSApp] updatgeDatabase: " +DATABASE_CREATE);
			db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
			onCreate(db);
		}
	}

	public DiaryDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	public DiaryDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void closeclose() {
		mDbHelper.close();
	}

	public long createDiary(String content, String sms_func_code,String sms_func_code_cn,String status,String reqid) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(CONTENT, content);
		initialValues.put(SMS_FUNC_CODE, sms_func_code);
		initialValues.put(SMS_FUNC_CODE_CN, sms_func_code_cn);
		initialValues.put(STATUS, status);
		initialValues.put(REQID, reqid);
		Calendar calendar = Calendar.getInstance();
		String created = calendar.get(Calendar.YEAR) + "年"
				+ calendar.get(Calendar.MONTH) + "月"
				+ calendar.get(Calendar.DAY_OF_MONTH) + "日"
				+ calendar.get(Calendar.HOUR_OF_DAY) + "时"
				+ calendar.get(Calendar.MINUTE) + "分";
		initialValues.put(CREATE_TIME, created);
		Log.i(TAG, "[SMSApp] insertsql: ");
		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteDiary(long rowId) {
		Log.i(TAG, "[SMSApp] deletesql: "+rowId);
		return mDb.delete(DATABASE_TABLE, PUSH_ID + "=" + rowId, null) > 0;
	}
	
	public boolean deleteAll() {
		Log.i(TAG, "[SMSApp] deleteallsql: ");
		return mDb.delete(DATABASE_TABLE, null, null) > 0;
		
	}

	public Cursor getAllMessage() {
		Log.i(TAG, "[SMSApp] getallsql: ");
		return mDb.query(DATABASE_TABLE, new String[] { PUSH_ID, CONTENT,
				SMS_FUNC_CODE, SMS_FUNC_CODE_CN,CREATE_TIME,STATUS,REQID }, null, null, null, null, null);
	}

	public Cursor getDiary(long rowId) throws SQLException {

		Cursor mCursor =

		mDb.query(true, DATABASE_TABLE, new String[] { PUSH_ID, CONTENT,
				SMS_FUNC_CODE, SMS_FUNC_CODE_CN,CREATE_TIME,STATUS,REQID }, PUSH_ID + "=" + rowId, null, null,
				null, null, null);
		Log.i(TAG, "[SMSApp] getDiarysql: ");
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	public boolean updateDiary(long rowId, String content, String sms_func_code,String sms_func_code_cn,String status,String reqid) {
		ContentValues args = new ContentValues();
		args.put(CONTENT, content);
		args.put(SMS_FUNC_CODE, sms_func_code);
		args.put(SMS_FUNC_CODE_CN, sms_func_code_cn);
		args.put(STATUS, status);
		args.put(REQID, reqid);
		Calendar calendar = Calendar.getInstance();
		String created = calendar.get(Calendar.YEAR) + "年"
				+ calendar.get(Calendar.MONTH) + "月"
				+ calendar.get(Calendar.DAY_OF_MONTH) + "日"
				+ calendar.get(Calendar.HOUR_OF_DAY) + "时"
				+ calendar.get(Calendar.MINUTE) + "分";
		args.put(CREATE_TIME, created);
		Log.i(TAG, "[SMSApp] updatesql: ");
		return mDb.update(DATABASE_TABLE, args, PUSH_ID + "=" + rowId, null) > 0;
	}
}

    由于SMSNotifyActivity 方法中listview中有按钮提交事件普通的listview不能响应事件,ListViewButtonAdapter

扩展BaseAdapter 方法重写getView 方法,添加BUTTON 并添加按钮响应事件

    package com.msi.manning;

Java代码 复制代码  收藏代码
  1. import java.util.ArrayList;   
  2. import java.util.HashMap;   
  3.   
  4. import android.content.Context;   
  5. import android.content.Intent;   
  6. import android.database.Cursor;   
  7. import android.util.Log;   
  8. import android.view.LayoutInflater;   
  9. import android.view.View;   
  10. import android.view.View.OnClickListener;   
  11. import android.view.ViewGroup;   
  12. import android.widget.BaseAdapter;   
  13. import android.widget.Button;   
  14. import android.widget.TextView;   
  15.   
  16. /**  
  17.  * 2011-4-20 上午10:56:21 lvButtonAdapter.java author:zhouhui  
  18.  * E-mail:wwwzhouhui@163.com  
  19.  */  
  20. public class ListViewButtonAdapter extends BaseAdapter {   
  21.     private DiaryDbAdapter mDbHelper;   
  22.     private static final String TAG = "lvButtonAdapter";   
  23.     public static final String ACTION_INTENT_TASKRECEIVER= "com.gift.android.TaskReceiver";   
  24.   
  25.     private class buttonViewHolder {   
  26.         // ImageView appIcon;   
  27.         TextView appName1;   
  28.         TextView appName2;   
  29.         TextView appName3;   
  30.         TextView appName4;   
  31.         TextView appName5;   
  32.         Button buttonClose;   
  33.         Button buttonView;   
  34.     }   
  35.   
  36.     private ArrayList<HashMap<String, Object>> mAppList;   
  37.     private LayoutInflater mInflater;   
  38.     private Context mContext;   
  39.     private String[] keyString;   
  40.     private int[] valueViewID;   
  41.     private buttonViewHolder holder;   
  42.   
  43.     public ListViewButtonAdapter(Context c,   
  44.             ArrayList<HashMap<String, Object>> appList, int resource,   
  45.             String[] from, int[] to, DiaryDbAdapter mDbHelper) {   
  46.         mAppList = appList;   
  47.         mContext = c;   
  48.         mInflater = (LayoutInflater) mContext   
  49.                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);   
  50.         keyString = new String[from.length];   
  51.         valueViewID = new int[to.length];   
  52.         System.arraycopy(from, 0, keyString, 0, from.length);   
  53.         System.arraycopy(to, 0, valueViewID, 0, to.length);   
  54.         this.mDbHelper = mDbHelper;   
  55.     }   
  56.   
  57.     @Override  
  58.     public int getCount() {   
  59.         return mAppList.size();   
  60.     }   
  61.   
  62.     @Override  
  63.     public Object getItem(int position) {   
  64.         return mAppList.get(position);   
  65.     }   
  66.   
  67.     @Override  
  68.     public long getItemId(int position) {   
  69.         return position;   
  70.     }   
  71.   
  72.     public void removeItem(int position) {   
  73.         mAppList.remove(position);   
  74.         this.notifyDataSetChanged();   
  75.     }   
  76.   
  77.     @Override  
  78.     public View getView(int position, View convertView, ViewGroup parent) {   
  79.         if (convertView != null) {   
  80.             holder = (buttonViewHolder) convertView.getTag();   
  81.         } else {   
  82.             convertView = mInflater.inflate(R.layout.list, null);   
  83.             holder = new buttonViewHolder();   
  84.             holder.appName1 = (TextView) convertView   
  85.                     .findViewById(valueViewID[0]);   
  86.             holder.appName2 = (TextView) convertView   
  87.                     .findViewById(valueViewID[1]);   
  88.             holder.appName3 = (TextView) convertView   
  89.                     .findViewById(valueViewID[2]);   
  90.             holder.appName4 = (TextView) convertView   
  91.                     .findViewById(valueViewID[3]);   
  92.             holder.appName5 = (TextView) convertView   
  93.                     .findViewById(valueViewID[4]);   
  94.             holder.buttonClose = (Button) convertView   
  95.                     .findViewById(valueViewID[5]);   
  96.             holder.buttonView = (Button) convertView   
  97.                     .findViewById(valueViewID[6]);   
  98.             convertView.setTag(holder);   
  99.         }   
  100.   
  101.         HashMap<String, Object> appInfo = mAppList.get(position);   
  102.         if (appInfo != null) {   
  103.             Long aname1 = (Long) appInfo.get(keyString[0]);   
  104.             String aname2 = (String) appInfo.get(keyString[1]);   
  105.             String aname3 = (String) appInfo.get(keyString[2]);   
  106.             String aname4 = (String) appInfo.get(keyString[3]);   
  107.             String aname5 = (String) appInfo.get(keyString[4]);   
  108.             holder.appName1.setText(String.valueOf(aname1));   
  109.             holder.appName2.setText(aname2);   
  110.             holder.appName3.setText(aname3);   
  111.             holder.appName4.setText(aname4);   
  112.             holder.appName5.setText(aname5);   
  113.             holder.buttonClose   
  114.                     .setOnClickListener(new lvButtonListener(position));   
  115.             holder.buttonView   
  116.                     .setOnClickListener(new lvButtonListener(position));   
  117.         }   
  118.         return convertView;   
  119.     }   
  120.   
  121.     class lvButtonListener implements OnClickListener {   
  122.         private int position;   
  123.   
  124.         lvButtonListener(int pos) {   
  125.             position = pos;   
  126.         }   
  127.   
  128.         @Override  
  129.         public void onClick(View v) {   
  130.             int vid = v.getId();   
  131.             if (vid == holder.buttonClose.getId()) {   
  132.                 boolean flag = mDbHelper.deleteDiary(Long   
  133.                         .parseLong((holder.appName1.getText().toString())));   
  134.                 Log.i(TAG, "[SMSApp] deletesql: " + flag);   
  135.                 removeItem(position);   
  136.             }   
  137.             if (vid == holder.buttonView.getId()) {   
  138.                 // 查看短信详细   
  139.                 ShowView(Long.parseLong((holder.appName1.getText().toString())));   
  140.             }   
  141.         }   
  142.   
  143.         private void ShowView(long id) {   
  144.             Cursor mDiaryCursor = mDbHelper.getDiary(id);   
  145.             if (mDiaryCursor != null) {   
  146.                 boolean flag = mDbHelper.updateDiary(id,   
  147.                         mDiaryCursor.getString(1), mDiaryCursor.getString(2),   
  148.                         mDiaryCursor.getString(3), "1",mDiaryCursor.getString(6));   
  149.                 Log.i(TAG, "[SMSApp] updatesql: " + flag);   
  150.                 // 广播消息   
  151.                 Intent intent = new Intent(ACTION_INTENT_TASKRECEIVER);   
  152.                 intent.putExtra("TaskContent", mDiaryCursor.getString(2)+"#"+mDiaryCursor.getString(6));   
  153.                 mContext.sendBroadcast(intent);   
  154.             }   
  155.         }   
  156.     }   
  157.   
  158. }  
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

/**
 * 2011-4-20 上午10:56:21 lvButtonAdapter.java author:zhouhui
 * E-mail:wwwzhouhui@163.com
 */
public class ListViewButtonAdapter extends BaseAdapter {
	private DiaryDbAdapter mDbHelper;
	private static final String TAG = "lvButtonAdapter";
	public static final String ACTION_INTENT_TASKRECEIVER= "com.gift.android.TaskReceiver";

	private class buttonViewHolder {
		// ImageView appIcon;
		TextView appName1;
		TextView appName2;
		TextView appName3;
		TextView appName4;
		TextView appName5;
		Button buttonClose;
		Button buttonView;
	}

	private ArrayList<HashMap<String, Object>> mAppList;
	private LayoutInflater mInflater;
	private Context mContext;
	private String[] keyString;
	private int[] valueViewID;
	private buttonViewHolder holder;

	public ListViewButtonAdapter(Context c,
			ArrayList<HashMap<String, Object>> appList, int resource,
			String[] from, int[] to, DiaryDbAdapter mDbHelper) {
		mAppList = appList;
		mContext = c;
		mInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		keyString = new String[from.length];
		valueViewID = new int[to.length];
		System.arraycopy(from, 0, keyString, 0, from.length);
		System.arraycopy(to, 0, valueViewID, 0, to.length);
		this.mDbHelper = mDbHelper;
	}

	@Override
	public int getCount() {
		return mAppList.size();
	}

	@Override
	public Object getItem(int position) {
		return mAppList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void removeItem(int position) {
		mAppList.remove(position);
		this.notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView != null) {
			holder = (buttonViewHolder) convertView.getTag();
		} else {
			convertView = mInflater.inflate(R.layout.list, null);
			holder = new buttonViewHolder();
			holder.appName1 = (TextView) convertView
					.findViewById(valueViewID[0]);
			holder.appName2 = (TextView) convertView
					.findViewById(valueViewID[1]);
			holder.appName3 = (TextView) convertView
					.findViewById(valueViewID[2]);
			holder.appName4 = (TextView) convertView
					.findViewById(valueViewID[3]);
			holder.appName5 = (TextView) convertView
					.findViewById(valueViewID[4]);
			holder.buttonClose = (Button) convertView
					.findViewById(valueViewID[5]);
			holder.buttonView = (Button) convertView
					.findViewById(valueViewID[6]);
			convertView.setTag(holder);
		}

		HashMap<String, Object> appInfo = mAppList.get(position);
		if (appInfo != null) {
			Long aname1 = (Long) appInfo.get(keyString[0]);
			String aname2 = (String) appInfo.get(keyString[1]);
			String aname3 = (String) appInfo.get(keyString[2]);
			String aname4 = (String) appInfo.get(keyString[3]);
			String aname5 = (String) appInfo.get(keyString[4]);
			holder.appName1.setText(String.valueOf(aname1));
			holder.appName2.setText(aname2);
			holder.appName3.setText(aname3);
			holder.appName4.setText(aname4);
			holder.appName5.setText(aname5);
			holder.buttonClose
					.setOnClickListener(new lvButtonListener(position));
			holder.buttonView
					.setOnClickListener(new lvButtonListener(position));
		}
		return convertView;
	}

	class lvButtonListener implements OnClickListener {
		private int position;

		lvButtonListener(int pos) {
			position = pos;
		}

		@Override
		public void onClick(View v) {
			int vid = v.getId();
			if (vid == holder.buttonClose.getId()) {
				boolean flag = mDbHelper.deleteDiary(Long
						.parseLong((holder.appName1.getText().toString())));
				Log.i(TAG, "[SMSApp] deletesql: " + flag);
				removeItem(position);
			}
			if (vid == holder.buttonView.getId()) {
				// 查看短信详细
				ShowView(Long.parseLong((holder.appName1.getText().toString())));
			}
		}

		private void ShowView(long id) {
			Cursor mDiaryCursor = mDbHelper.getDiary(id);
			if (mDiaryCursor != null) {
				boolean flag = mDbHelper.updateDiary(id,
						mDiaryCursor.getString(1), mDiaryCursor.getString(2),
						mDiaryCursor.getString(3), "1",mDiaryCursor.getString(6));
				Log.i(TAG, "[SMSApp] updatesql: " + flag);
				// 广播消息
				Intent intent = new Intent(ACTION_INTENT_TASKRECEIVER);
				intent.putExtra("TaskContent", mDiaryCursor.getString(2)+"#"+mDiaryCursor.getString(6));
				mContext.sendBroadcast(intent);
			}
		}
	}

}

    layout 文件的布局管理文件

    main.xml

    <?xml version="1.0" encoding="utf-8"?>

Xml代码 复制代码  收藏代码
  1. <RelativeLayout android:id="@+id/RelativeLayout01"  
  2.     android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_height="wrap_content" android:paddingBottom="4dip"  
  4.     android:paddingLeft="12dip" android:paddingRight="12dip"  
  5.     android:descendantFocusability="blocksDescendants" >     
  6.     <ListView android:layout_width="wrap_content"      
  7.                   android:layout_height="400dip"      
  8.                   android:id="@+id/MyListView">     
  9.      </ListView>  
  10.          <LinearLayout  
  11.             android:id="@+id/bottom_panel"  
  12.             android:layout_width="fill_parent"  
  13.             android:layout_height="wrap_content"  
  14.             android:orientation="horizontal"  
  15.             android:gravity="center_horizontal"  
  16.             android:layout_alignParentBottom="true"  
  17.             >  
  18.             <Button android:id="@+id/btn_config_clear"  
  19.             android:layout_width="wrap_content"  
  20.             android:layout_height="wrap_content"  
  21.             android:width="100dip"  
  22.             android:text="清空" />    
  23.             <Button android:id="@+id/btn_config_close"  
  24.             android:layout_width="wrap_content"  
  25.             android:layout_height="wrap_content"  
  26.             android:width="100dip"  
  27.             android:text="退出" />  
  28.             </LinearLayout>  
  29. </RelativeLayout>    

    list.xml

    <?xml version="1.0" encoding="utf-8"?>

Xml代码 复制代码  收藏代码
  1. <!-- 此布局文件用来定义listview 的显示方式 -->  
  2. <RelativeLayout android:id="@+id/RelativeLayout01"  
  3.     android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_height="wrap_content" android:paddingBottom="4dip"  
  5.     android:paddingLeft="12dip" android:paddingRight="12dip"  
  6.     android:descendantFocusability="blocksDescendants" >  
  7.     <TextView android:layout_height="wrap_content"  
  8.         android:textSize="20dip" android:layout_width="fill_parent"    
  9.         android:id="@+id/ItemTitle" />  
  10.     <TextView android:layout_height="wrap_content"  
  11.         android:layout_width="fill_parent"  android:layout_below="@+id/ItemTitle"  
  12.         android:id="@+id/ItemType" />  
  13.     <TextView android:layout_height="wrap_content" android:layout_below="@+id/ItemType"  
  14.         android:layout_width="fill_parent"    
  15.         android:id="@+id/ItemTime" />  
  16.     <TextView android:layout_height="wrap_content"  
  17.         android:layout_width="fill_parent" android:layout_below="@+id/ItemTime"  
  18.         android:id="@+id/ItemStatus" />  
  19.     <TextView android:layout_height="wrap_content"  
  20.         android:layout_width="fill_parent" android:layout_below="@+id/ItemStatus"  
  21.         android:id="@+id/ItemText" />  
  22.         <Button android:id="@+id/btn_config_view"  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:layout_below="@+id/ItemText"  
  26.             android:layout_alignParentRight="true"  
  27.             android:focusable="false"  
  28.             android:width="50dip"  
  29.             android:text="查看" />  
  30.         <Button android:id="@+id/btn_config_delete"  
  31.             android:layout_width="wrap_content"  
  32.             android:layout_height="wrap_content"  
  33.             android:layout_toLeftOf="@+id/btn_config_view"  
  34.             android:layout_alignTop="@+id/btn_config_view"  
  35.             android:focusable="false"  
  36.             android:width="50dip"  
  37.             android:text="删除" />  
  38. </RelativeLayout>    

    AndroidManifest.xml

    中 添加手机自启动注册信息android.permission.RECEIVE_BOOT_COMPLETED

    添加广播监听

    <receiver android:name=".BootReceiver">

<intent-filter android:priority="100">

<action android:name="android.intent.action.BOOT_COMPLETED" />

<action android:name="android.provider.Telephony.SMS_RECEIVED" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

    </receiver>

    这里添加短信监听广播接收android.provider.Telephony.SMS_RECEIVED

    完整的AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>

Xml代码 复制代码  收藏代码
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     package="com.msi.manning">  
  3.     <application android:icon="@drawable/chat">  
  4.         <activity android:name="com.msi.manning.SMSNotifyActivity"  
  5.             android:label="@string/app_name" android:clearTaskOnLaunch="true">  
  6.             <intent-filter>  
  7.                 <action android:name="android.intent.action.MAIN" />  
  8.                 <category android:name="android.intent.category.LAUNCHER" />  
  9.             </intent-filter>  
  10.         </activity>  
  11.         <receiver android:name=".BootReceiver">  
  12.             <intent-filter android:priority="100">  
  13.                 <action android:name="android.intent.action.BOOT_COMPLETED" />  
  14.                 <action android:name="android.provider.Telephony.SMS_RECEIVED" />  
  15.                 <category android:name="android.intent.category.LAUNCHER" />  
  16.             </intent-filter>  
  17.         </receiver>  
  18.     </application>  
  19.     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  
  20.      <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <!-- 程序接收短信权限 -->  
  21.     <uses-permission android:name="android.permission.READ_SMS"></uses-permission>  <!-- 读短信权限 -->  
  22. </manifest>   

 


 

 

  • 大小: 23 KB
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值