[android]代码库
// 监听注册
public void register(Handler handler, IProcessObser processObser)
{
mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mSmsObserver);
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
filter.setPriority(Integer.MAX_VALUE);
mContext.registerReceiver(mSmsReceive, filter);
mSmsHandler.addProcessObser(handler, processObser);
}
// 反注册
public void unRegister()
{
mContext.getContentResolver().unregisterContentObserver(mSmsObserver);
mContext.unregisterReceiver(mSmsReceive);
mSmsHandler.removeProcessObser();
}
// 销毁工作线程
public void destory()
{
mThreadExitFlag = true;
synchronized (mWorkThread) {
mWorkThread.notify();
}
}
class SmsObserver extends ContentObserver
{
public SmsObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
@Override
public void onChange(boolean selfChange) {
// TODO Auto-generated method stub
super.onChange(selfChange);
// onChange的执行是在UI线程里做的,所以不能直接去做遍历数据库的耗时操作
synchronized (mWorkThread) {
mWorkThread.notify(); // 唤醒工作线程
}
}
}
class WorkThread extends Thread
{
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mThreadExitFlag == true)
{
break;
}
}
try {
mSmsHandler.doWork();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class SMSReceive extends BroadcastReceiver {
private final static String TAG = "SMSReceive";
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
SmsInfo smsInfo = new SmsInfo();
StringBuffer sBuffer = new StringBuffer();
for(int n = 0; n < messages.length; n++)
{
smsMessage[n]= SmsMessage.createFromPdu((byte[]) messages[n]);
sBuffer.append(smsMessage[n].getMessageBody());
smsInfo.address = smsMessage[n].getOriginatingAddress();
}
smsInfo.body = sBuffer.toString();
smsInfo.date = String.valueOf(System.currentTimeMillis());
if (SmsFilter.isFilter(smsInfo)) // 过滤短信并处理
{
abortBroadcast();
mSmsHandler.processSMSInfo(smsInfo);
}
}
}
[源代码打包下载]
初级程序员
by: 云代码会员 发表于:2014-03-25 19:29:48 顶(0) | 踩(0) 回复
想问问这种方式对现在的qq通讯里有用吗? 谢谢
回复评论