2017-01-19 23 views
0

我是新來的Android編程和我做的作品像這樣的應用程序:從短信接收輸入一些「命令」(格式-command文件名)之後,它會讀取郵件內容,並執行特定的多媒體在應用程序的另一個活動中的操作。如何在同一個活動中調用兩個方法,這些方法可以在同一個文件上工作,但在不同的時間?

問題是,當一個SMS中有相同的文件工作的命令(例如「-SHOTPHOTO photo1 -SENDPHOTO photo1」)時,應用程序調用這兩種方法來執行此操作,但只有第一個方法正確執行;另一個返回一個錯誤,因爲照片還沒有被拍攝。

// 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照片2 -SENDPHOTO照片1 -SHOTPHOTO照片1。我測試了閱讀和正確性控制過程,並沒有問題。 所以我認爲我的問題是這兩種方法同時執行,並且sendphoto()沒有找到照片,因爲它尚未拍攝。

就如何使這兩種方法sinchronized,使得第一命令在第二個之前總是執行,而第二個等待第一個完成的一些想法?

因爲它不是我想要什麼,我不會添加一個命令「-SHOTNSEND photoName」。將shotphoto()添加到shotphoto()的結尾將不允許我在未實際發送照片的情況下拍攝照片。

我寫到這裏的代碼只是一個真正的代碼非常簡單的例子,讓我知道,如果事情是不明確或者一些真正重要的是缺少。

+0

而不是對,讓排隊的所有命令。當第一個完成時執行下一個命令 – X3Btel

+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的回答!

相關問題