【问题标题】:how to make Main Activity thread affect Second Activity如何使主活动线程影响第二个活动
【发布时间】:2017-06-17 08:52:39
【问题描述】:

我的MainActivity 有一个Thread,它会生成 RSA 密钥并返回生成密钥所需的时间(以毫秒为单位)。

当我运行这个Thread 时,应用程序转到第二个Activity

我需要第二个Activity 以毫秒为单位接收该时间。

据我了解,一旦您致电 startActivity(),父母 Activity 就会进入睡眠状态。那么如何同时运行两者呢?

谢谢!

【问题讨论】:

  • 使用广播接收器来通知甚至监听您的 RAS 密钥的人。
  • 谢谢!我会调查的

标签: java android multithreading android-activity


【解决方案1】:

您可以使用 LocalBroadcastReceiver。

public class SecondActivity extends AppCompatActivity {

private BroadcastReceiver mRsaReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        ArrayList<String> rsaList = intent.getStringArrayListExtra("rsaList");
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
    LocalBroadcastManager.getInstance(this).registerReceiver(mRsaReceiver, new IntentFilter("RSA"));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRsaReceiver);
}

}

来自您的 rsa 线程

Intent rsaIntent = new Intent("RSA");
rsaIntent.putExtra("rsaList", rsaArrayList);
LocalBroadcastManager.getInstance(context).sendBroadcast(rsaIntent);

【讨论】:

    【解决方案2】:

    据我了解,一旦您 startActivity(),父 Activity 就会进入睡眠状态。那么如何同时运行两者

    你没有。你不需要。由于您在单独的线程上生成 RSA 密钥,因此代码应该完全独立于您的活动(除了在 MainActivity 中启动)。因此,您只需要知道后台任务何时完成 - 为此您可以使用应用内 broadcasts 或使用事件总线(如 GreenRobot's EventBus 库)或使用 RxJava

    【讨论】:

    • 谢谢!我要开始研究广播了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多