我正在开发一个 Android 应用程序来阻止传入的 SMS 消息并在执行一些过程后释放它们。
我想要做的是,当收到短信时需要阻止该消息并将其推送到在线服务器。之后,管理员可以查看通过网站推送到服务器的那些消息,并且他/她可以批准或拒绝。如果管理员批准该消息,则需要将其发布到电话收件箱,否则丢弃该消息。
我完成了除了一件事之外的所有事情。我所做的是在消息推送到服务器后,将启动一个计划的计时器任务,每 5 分钟读取一次在线服务器,并检查消息是否被批准。我正在使用“BroadcastReceiver”来跟踪传入的消息,并且我知道要释放被阻止的消息,我应该在“onReceive”方法结束之前使用“clearAbortBroadcast()”方法。但是我的计时器充当线程。因此,如果我在计时器内调用“clearAbortBroadcast()”方法,则“onReceive”方法已经完成执行并且消息不会被释放。
有人可以帮助我克服这个问题。
我的广播接收器类
public class SmsReceiver extends BroadcastReceiver{
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
public static long NOTIFY_INTERVAL = 15000;
int id;
Context context;
SmsReceiver sr;
GetMsgStatus status;
Bundle bundle;
@Override
public void onReceive(Context context, Intent intent)
{
//this stops notifications to others
this.abortBroadcast();
this.context = context;
//create a instance of GetMsgStatus class
status = new GetMsgStatus(context);
//---get the SMS message passed in---
bundle = intent.getExtras();
SmsMessage[] msgs = null;
String from = null;
String to = null;
String msg= null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
from = msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
msg = msgs[i].getMessageBody().toString();
str += "\n";
}
System.out.println("from "+from);
System.out.println("msg "+msg);
Toast.makeText(context, "SMS Received : ",Toast.LENGTH_LONG).show();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
to = mTelephonyMgr.getLine1Number();
//push msg to the server
SendMsgToServer send = new SendMsgToServer(context, to, from, msg);
//get the msg id of the pushed msg
id = send.getId();
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
}
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run()
{
status.getDataFromServer(id);
//if status is 0 means msg rejected
if(status.getStatus()==0)
{
mTimer.cancel();
}
//if status is 1 means msg approved
else if(status.getStatus()==1)
{
sr.clearAbortBroadcast();
mTimer.cancel();
}
//pending
else
{
System.out.println("pending");
}
}
});
}
}
}