Android 短信发送代码损坏
好的,所以我正在制作一个 Android 应用程序,它能够多次发送短信,并且发送的消息量之间有一定的间隔。这部分起作用,但有时不起作用。例如,当我输入 20 条消息来发送时,它会发送 16 条或更多。另外,当我按下按钮时,它会冻结,直到完成发送短信。无论如何,有人可以告诉我我的代码有什么问题吗?我尝试了一些效果不佳的修复程序,并认为在多次失败的尝试后我会来这里寻求帮助。 PS 还有更多的代码,但这就是我相信问题所在的地方。感谢您的阅读 编辑:已修复!
Ok, so i am making a Android app that is able to send sms msgs multiple times with intervals between the amount of messages is sent. This is partially working but it sometimes does not. For example when i input 20 msgs to send it sends 16 or maybe a little more. Also when i push the button it freezes until it finishes sending the SMS's.is there anyway that someone could tell me what is wrong with my code? i have tried a few fixs that are not working very well and thought i would come here for help after many failed trys at this. PS there is more code then this but this is where the issue resides i beleive. Thanks for reading
EDIT: FIXED!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该按钮处于“冻结”状态,因为 UI 线程正在发送所有 20 条短信,然后才能腾出时间来做其他事情。
我会研究 AsyncTask。这是 Android 轻松线程化的方式。本质上,您要做的就是使用 AsyncTask 在后台生成一个新线程。这会释放 UI 线程,使用户看起来一切正常(不会冻结),而 AsyncTask 则通过
doInBackground
在后台完成所有工作。然后,当任务完成时,使用 onPostExecute 通知 UI 任务已完成,并可能告诉用户一些信息。您可以在 onClick 中调用MyAsyncTask.execute(smsDataHere)
。出于简单目的,AsyncTask 的链接相当全面,并且包含示例代码。
我不确定到底为什么它只发送 16 条左右的消息,但我可以立即看到您缺少一些花括号,并且它们与您想要的方式不太匹配他们到。我会先看看那里。另外,第二个 for 循环是否有原因?
size
始终为 1,因此每条消息仅发送两次。编辑:
这是一些示例代码。我不会保证它在您的应用程序中有效,但它会向您展示 AsyncTask 的工作原理并为您提供一个起点。我还尝试解决花括号的任何问题并做了一些清理工作。我仍然建议您查看文档以确保您了解它是如何工作的。我希望这对你有帮助。
The button is "freezing" because the UI thread is sending all 20 SMS before it frees up to do other things.
I would look into AsyncTask. This is Android's way to easily thread. Essentially what you would do it spawn a new thread in the background with AsyncTask. This frees up the UI thread so that it looks like everything is normal to the user (no freezing), while the AsyncTask is doing all of the work in the background with
doInBackground
. Then when the Task is done useonPostExecute
to notify the UI that it is done and perhaps tell the user something. You'd put the call toMyAsyncTask.execute(smsDataHere)
in the onClick.That link to AsyncTask is fairly comprehensive for simple purposes and has example code.
I'm not sure exactly why it only send 16 or so messages, but I can see right off the bat that you are missing some curly braces and that they don't quite match up the way you want them to. I would look there first. Also, is there a reason for the second
for
loop?size
is always 1, so it is just sending each message twice.EDIT:
Here is some sample code. I'm not going to promise it works in your exact app, but it will show you how the AsyncTask works and give you a starting point. I also tried to fix any problems with the curly braces and did a little cleaning up. I still recommend looking over the documentation to make sure you understand how it works. I hope this helps you.