gpt4 book ai didi

android - 如何等待确认短信在 AsyncTask 中发送?

转载 作者:太空狗 更新时间:2023-10-29 14:13:17 27 4
gpt4 key购买 nike

我正在尝试在我的 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) {

}
}

我在我的代码中加入了解释。因此,我需要知道消息是否已发送,然后才能继续发送其他消息。实现该目标的最佳方法是什么?

最佳答案

你必须为 Intent Filter Sent 注册一个广播接收器,在那里你可以得到消息发送的事件。取一个 bool 值作为

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) {

}

当消息被发送时,这个循环将被终止并发送下一条消息。

关于android - 如何等待确认短信在 AsyncTask 中发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com