我正在开发一款Android应用来阻止传入的短信,并在完成某些过程后将其释放。
我想要做的是,当收到短信时,需要阻止该短信并将其推送到在线服务器。之后,管理员可以查看通过网站推送到服务器的消息,他/她可以批准或拒绝。如果管理员批准该消息,则需要将其发布到手机收件箱,否则会丢弃该消息。
除了一件事,我完成了所有事情。我所做的是在消息被推送到服务器后,将启动预定的计时器任务并每隔5分钟读取一次在线服务器并检查天气消息是否被批准。我正在使用" BroadcastReceiver"跟踪收到的消息我知道要发布阻止的消息,我应该使用" clearAbortBroadcast()"之前的方法" onReceive"方法结束。但我的计时器充当线程。所以,如果我打电话给" clearAbortBroadcast()"定时器里面的方法" onReceive"方法已经完成执行,消息没有被释放。
有人可以帮我解决这个问题。
我的BroadcastReceiver类
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");
}
}
});
}
}
}
答案 0 :(得分:0)
BroadcastReceiver不应该活得那么多,所以你不能依赖clearAbortBroadcast()。
在你的情况下,我认为你的流程将是:
我不认为这种检查是好的,但你可能有你的理由,只要确保安装它的用户知道它的作用。