我的应用程序具有针对特定意图的广播接收器(由系统应用触发),必须针对该意图返回结果。这本身并不困难。
但是,该结果将基于从另一个应用程序到另一个广播接收者的广播意图的结果。因此,是一个嵌套序列。
所以基本上:
系统应用->意向 这个程序->意图 另一个应用 <-结果 <-结果
但是找不到一种方法,可以在我的接收者处理完自己收到的意图之前,将该意图从我的应用程序触发到另一个应用程序。
我在线程,处理程序等方面玩了很多,但核心问题似乎是sendbroadcast由应用程序的主循环执行,该循环一直等待到广播接收器onReceive从其任务返回。
代码示例是我代码的框架。它显示了我需要实现的基础知识。
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(CustomIntent.EDIT_DATA)) {
// we nest the intent to the other app
final Bundle resultBundle = new Bundle();
final Intent editdataIntent = new Intent(action);
editdataIntent.setComponent(ExplicitOtherAppComponent);
editdataIntent.putExtras(intent.getExtras());
final Object monitor = new Object();
HandlerThread thread = new HandlerThread("BroadcastReceiverThread");
thread.start();
synchronized (monitor) {
handlerContext.sendOrderedBroadcast(editdataIntent, null, new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle results = getResultExtras(false);
String pluginBarcodeData = results.getString("data");
resultBundle.putString("data", pluginBarcodeData);
synchronized(monitor) {
monitor.notify();
}
}
}, new Handler(thread.getLooper()), Activity.RESULT_OK, null, null);
try {
monitor.wait(1000); // timeout for receiving the result
} catch (InterruptedException e) {
}
}
thread.quit();
final PendingResult result = goAsync();
result.setResultExtras(resultBundle);
result.setResultCode(1);
result.finish();
}
}
如何在结束自己的onReceive之前使广播被发送,结果被接收?我的应用程序需要根据嵌套应用程序中的信息返回结果。
由于系统应用程序的超时限制,整个解决方案需要在不到一秒钟的时间内回复。该解决方案是条形码扫描解决方案的一部分,用户需要/期望在扫描条形码后立即听到成功提示音。当插件返回并返回已扫描的条形码有效的答复时,将首先发出蜂鸣声,因此,由于异步操作而引起的任何延迟都将成为不可能。