如何阻止主Android线程直到收到Intent?

时间:2012-03-30 08:13:18

标签: android multithreading process

我想阻止应用程序的执行(比方说A),直到另一个应用程序(比方说B)发送一个Intent。我知道阻塞具有无限循环的线程并不好,但出于安全原因,我确实需要保证在收到Intent之前不会执行A的代码。在阻止应用程序A之前,我使用Intent启动另一个应用程序B.这样,应用程序A将有机会生存直到B完成。为此,我目前编写了一个阻塞循环,例如:

 context.startActivity(message); // starting app B

 // Blocking A
 while (condition) // waits an authorization from B
 { 
    Thread.sleep(5000);
    // some checks can be done here to modify the condition evaluation
    // for example, check the Intents received from B
 }
 // (Secured zone) 
 // Some code that should not be executed before that the condition is true

我尝试了很多解决方案来检查Intent接收:

  • 使用broadcastreceiver是不可能的,因为主线程永远不会有机会处理收到的Intent
  • 使用绑定服务到另一个应用程序来获取信息:同样,不会调用onConnectedService方法,因为主线程不会处理该事件。
  • 使用第二个独立的进程,该进程将被通知传入的Intent:这很有效。第二个进程被通知但是它无法通知主线程发生了某些事情!
  • 使用第二个Thread检查收到的Intents,绑定服务到B:没办法,第二个Thread不负责处理消息。

也许我错过了一个简单的解决方案,但我开始认为我正在尝试做一些与Android的哲学相矛盾的事情......

编辑:另一个限制是代码的“安全区域”部分无法移动到我的程序的其他位置......

3 个答案:

答案 0 :(得分:0)

主线程中的Thread.sleep()不是一个好主意。 您是否尝试重写活动A中的onNewIntent()方法以处理活动B发送的意图?

答案 1 :(得分:0)

它认为你应该使用另一种方法: 运行appA和appA内部,你应该做的第一件事就是运行appB并等到结果。 获得结果后,继续运行appA。

我看到的伪代码:

AppA()
{
  run app B;
  if (b return needed result)
  {
    rest of code of AppA...
    ....
    ....
  }
}

答案 2 :(得分:0)

我找到了解决问题的丑陋方式。在暂停应用A之后,应用A正在等待来自B的意图,该意图在不同的进程中执行。然后,当此进程从B接收消息时,它将信息写入文件。 A thas的主线程被阻塞到循环中,定期读取文件。当文件包含预期信息时,条件变为false并且线程被解除阻塞。

详细说明,它给出了:

进入应用程序A:

Thread.sleep(1000);

context.startActivity(message); // starting app B

// Blocking A
while (!auth) // waits an authorization from B
{ 

try {
  FileInputStream fIn = c.openFileInput("authorization.txt");
  InputStreamReader isr = new InputStreamReader(fIn);
  char buf[] = new char[1];
  isr.read(buf);
  String res = new String(buf);
  isr.close();

  if (res.equals("1"))
  {
  auth = true;
  System.out.println("READ OK");
  }
}

在应用程序A中,应使用android:process标签“:p2”在清单中声明广播接收器:

<receiver android:name="reporter.ReporterReceiver"  android:process=":p2">
  <intent-filter>
  <action android:name="andro.jf.reporterResponse" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

接收者应该是:

public class ReporterReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
    Bundle extra = intent.getExtras();

    System.out.println("ANSWER RECEIVED");

    if (extra != null)
    {
    String auth = extra.getString("authorization");
    //Reporter.authorization = contact;

    // Write the string to the file
    try {
        FileOutputStream fOut = context.openFileOutput("authorization.txt", Context.MODE_PRIVATE );
        OutputStreamWriter osw = new OutputStreamWriter(fOut); 
        osw.write(auth);
        osw.flush();
        osw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}
}

我知道,这很难看......但它起作用了,至少在模拟器中是这样。

相关问题