我是Android编程的新手,我正在创建一个这样的应用程序:在收到来自SMS的输入后,使用了一些"命令" (以-COMMAND文件名的形式),它读取消息的内容并在应用程序的另一个活动中执行某些多媒体操作。
问题在于,当一个SMS中的命令在同一个文件上工作时(例如" -SHOTPHOTO photo1 -SENDPHOTO photo1"),App会调用这两种方法,但只有第一个是执行正确;另一个返回错误,因为照片仍然没有被拍摄。
// onCreate of the new Activity
// I received an Intent from an SMS Broadcast Receiver
// The commands and file names are saved in order in command[nCommands] and files[nFiles], nCommands and nFiles are integer and represents the number of commands/file names
for (int i = 0; i < nCommands; i++) {
switch (command[i]) {
case "-SHOTPHOTO":
// finds the correct file name of this command
shotphoto(files[j]);
break;
case "-SENDPHOTO":
// finds the correct file name of this command
sendphoto(files[j]);
break;
}
}
// end of onCreate
public void shotphoto (String photoName) {
// standard method to take photos: calls the default camera app with startActivity
// takes photo and then renames it to photoName
// photo saved in the ExternalStorage, in my app folder
}
public void sendphoto(String photoName) {
// standard method to send email + photo: calls the default mail app with startActivity
// gets the photo from my app's folder in the ExternalStorage
// the photo is sent to the sender's mail address, which is already known
}
当两个命令在两个不同的消息中或者例如,在消息中有-SHOTPHOTO photo1而另一个消息中有-SHOTPHOTO photo2 -SENDPHOTO photo1时,我没有任何问题。我测试了阅读和正确性控制过程,它没有问题。 所以我认为我的问题是两个方法同时执行,而sendphoto()没有找到照片,因为它还没有被拍摄。
关于如何使两个方法同步的一些想法,以便第一个命令总是在第二个命令之前执行而第二个命令等待第一个命令完成?
我不会添加命令&#34; -SHOTNSEND photoName&#34;因为它不是我想要的。将sendphoto()添加到shotphoto()的末尾不会允许我在没有实际发送的情况下拍照。
我在这里写的代码只是真实代码的一个非常基本的例子,让我知道一些事情是不清楚的还是缺少一些非常重要的事情。
答案 0 :(得分:0)
我按照@ X3Btel的建议排队,我解决了我的问题。 对于那些想知道我是怎么做的人,这里是代码:
private Queue<String> qCommands; // global
public void onCreate(...){
qCommands = new ArrayDeque<>();
// read SMS' text
qCommands.add(command[i]); // everytime I read a command
// same as before but without for(i->nCommands) and switch command[i]
nextCommand(qCommands.poll());
}
public void nextCommand(String command){
if(command != null){
switch (command) {
case "-SHOTPHOTO":
// finds the correct file name of this command
shotphoto(files[j]);
break;
case "-SENDPHOTO":
// finds the correct file name of this command
sendphoto(files[j]);
break;
}
} else {
// the queue is empty so no more commands
}
// both shotphoto() and sendphoto() start an Activity for result so when they have finished onActivityResult will be called
public void onActivityResult(...){
if(resultcode == SHOTPHOTO)
nextCommand(qCommands.poll());
if(resultcode == SENDPHOTO)
nextCommand(qCommands.poll());
}
该应用有效,并且不像以前那样返回错误。 再次感谢@ X3Btel,谢谢你的回答!