gpt4 book ai didi

java - 如何使用第二个线程的 "startActivity"将 Intent 传递给主线程?

转载 作者:行者123 更新时间:2023-11-29 04:09:01 28 4
gpt4 key购买 nike

我想将 Intent 与 start(Intent) 一起使用,并执行由 Thread 控制的不同事情。我知道我需要主上下文才能使用“startActivity”,但如何从单独的线程管理它?是否可以使用处理程序或其他方式将“startActivity”链接到主线程?

使用示例:

Public Classic mThread implements Runnable{ 
@override
Public void Run()
{
If (true) //something is true
{
Intent intent = new Intent (Bluetoothadapter.Enable()):
startActivity(Intent):
}
If(true) //Something else is true
{
Intent intent = new Intent (MainActivity, esp.class);
startActivity (intent)
}
}
}

更新

这是我遇到问题的代码:

public class cBT_startcheck extends MainActivity implements Runnable {

private int iCurrent_BT_state = mBluetoothAdapter.getState();
@Override
public void run() {
if (mBluetoothAdapter == null) {
cGlobal_values.bBT_NOADAPTER =true;

}else if (mBluetoothAdapter != null)
{
cGlobal_values.bBT_NOADAPTER =false;
switch (iCurrent_BT_state)
{
case BluetoothAdapter.STATE_ON:
cGlobal_values.bBT_GenState_on=true;
break;

case BluetoothAdapter.STATE_OFF:
cGlobal_values.bBT_GenState_on =false;
break;
}
if (!mBluetoothAdapter.isEnabled()){
Log.d("HALLO", "run: ");
//Intent intBT_start = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//mainContext.startActivity(intBT_start);
vStart_BT();
}
}

}
}

主 Activity

这是我在MainActivity中做的

public class MainActivity extends AppCompatActivity {
public Handler mainHandler = new Handler(Looper.getMainLooper());
public void vStart_BT()
{
mainHandler.post(new Runnable() {
@Override
public void run() {
Intent intBT_start = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intBT_start);
}
});

}
}

问题

如何从写在单独类中的第二个线程执行一些 Intent?

如果这个想法本身不对:

我不知道如何使用“starActivity”将 Intent 传递给主线程。

最佳答案

您需要链接到上下文、 Activity 或任何 Activity View 。使应该在主线程中执行的代码可运行

Runnable your_code = new Runnable({
@Override
public void run(){
Intent intent = new Intent(context, MyActivity.class);
startActivity(intent);
}
};

对于上下文:

Looper looper = context.getMainLooper(); //Looper of main thread
Handler handler = new Handler(looper);
handler.post(your_code); //send your code to executing in main thread

Activity :

activity.runOnUiThread(your_code)

查看:

view.post(your_code)

关于java - 如何使用第二个线程的 "startActivity"将 Intent 传递给主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260214/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com