【问题标题】:Put onReceive on wait until the started activity finishes将 onReceive 置于等待,直到启动的活动完成
【发布时间】:2017-07-04 11:53:05
【问题描述】:

在 onReceive() 中,我想创建一个新的 Intent 并启动一个新的 Activity。活动结束后,我想回到我离开活动的地方。我知道我不能使用 BroadcastReceiver 类来实现这一点。如何实现?下面是 onReceive() 代码:

final BroadcastReceiver mPairingRequestRecevier = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(intent.getAction()))
        {
            final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);

            if (type == BluetoothDevice.PAIRING_VARIANT_PIN)
            {
                abortBroadcast();
                String passkey="hey";
                Intent passkeyIntent = new Intent(context.getApplicationContext(),TestActivity.class);
                passkeyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                passkeyIntent.putExtra("passkey",passkey);
                context.startActivity(passkeyIntent);
                Log.d("after returning...",passkey);

            }
            else
            {
                Log.d("Unexpected pairingtype:" , type+"");
            }
        }
    }
};

任何可以实现这一点的想法将不胜感激。

【问题讨论】:

  • “活动结束后,我想回到我离开活动的同一行”——这是不可能的。 startActivity() 是异步的。在startActivity() 返回时,将不会采取任何重大步骤来启动其他活动。在onReceive() 返回并且您将主应用程序线程的控制权交还给框架之前,真正的工作不会开始。您的 TestActivity 需要做您考虑让接收者做的任何工作。
  • 同一行是什么意思?
  • @CommonsWare 是的,你是对的。你知道如何实现它。也许我缺少正确的类或方法名称或某些标志。你能推荐一下吗?
  • @AndyDeveloper 同一行,我指的是context.startActivity(passkeyIntent);之后的行
  • “你知道如何实现吗”——将受影响的代码移动到活动中。接收者开始活动就是这样

标签: android android-intent android-broadcastreceiver


【解决方案1】:

您可以使用 startActivityFor 结果而不是 startActivity 来启动一个活动..让它执行一些任务并将结果返回到以前的活动 看这个:How to manage `startActivityForResult` on Android?

【讨论】:

  • BroadcastReceive 没有 startActivityForResult()。
  • @AnkitShubham:正确,但您的 BroadcastReceiver 在其他组件中。如果那是一个活动,您可以在包含此接收器的活动上使用startActivityResult()
  • @CommonsWare 不幸的是,BroadcastReceiver 不在活动中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多