我正在尝试在AsyncTask中发送一些消息,并且我想跟踪已发送消息的进度。感谢@cYrixmorten关于这个主题的精彩帖子https://stackoverflow.com/a/19084559/3339562我完成了大部分我想要的事情。这是我的代码:
@Override
public void onCreate(Bundle savedInstanceState) {
sentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent in) {
switch (getResultCode()) {
case Activity.RESULT_OK:
break;
default:
break;
}
}
};
getActivity().registerReceiver(sentReceiver, new IntentFilter(
SENT));
}
public class SomeAsyncTask extends
AsyncTask<ArrayList<Person>, Integer, Void> {
private ProgressDialog dialog;
private Context context;
public SomeAsyncTask(Activity activity) {
context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
this.dialog.show();
}
@Override
protected Void doInBackground(ArrayList<Person>... params) {
dialog.setMax(params[0].size());
SmsManager mySMS = SmsManager.getDefault();
for (int i = 0; i < params[0].size(); i++) {
Intent sentIn = new Intent(SENT);
PendingIntent sentPIn = PendingIntent.getBroadcast(context,
i, sentIn, 0);
mySMS.sendTextMessage(params[0].get(i).getNum(),
null, message, sentPIn, null);
// HERE I NEED TO WAIT TO RECEIVE CONFIRMATION THAT MESSAGE IS SENT AND
// THEN I CAN PUBLISH PROGRESS. HOW TO DO THAT RESULT IN onReceive() IN BroadcastReceiver()?
publishProgress((int) ((i / (float) params[0].size()) * 100));
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Void v) {
}
}
我在我的代码中加了解释。所以,我需要知道在我继续发送其他消息之前发送的消息。什么是实现这一目标的最佳方式?
答案 0 :(得分:1)
您必须为意向过滤器注册广播接收器已发送,您可以在那里获取发送的消息事件。取一个布尔值
bool isMessageSent= false;
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
// set boolean here to true
isMessageSent = true;
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
// handle your result
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
// handle your result
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
// handle your result
break;
default:
// handle your result
break;
}
}
}, new IntentFilter(SENT));
现在,在doInBackground方法中,将while循环添加为
while(!isMessageSent) {
}
当发送消息时,此循环将被终止,并且将发送下一条消息。