简体   繁体   English

如何在不冻结 UI 的情况下在 Android 中运行无限循环?

[英]How to run an infinite loop in Android without freezing the UI?

I'm creating and android program which needs to to continuously keep sending data over the bluetooth now I use something like this:我正在创建一个 android 程序,它需要不断地通过蓝牙发送数据,现在我使用这样的东西:

for(;;)
{
//send message
}

though this works it freezes my UI and app how can I implement the same without freezing my UI?虽然这有效,但它冻结了我的 UI 和应用程序,我如何在不冻结我的 UI 的情况下实现相同的功能?

I am sure that the app is sending the data as I monitor the data.我确信应用程序在我监控数据时正在发送数据。

Put your loop in an AsyncTask ,Service with separate Thread or just in another Thread beside your Activity.将您的循环放在AsyncTask中,带有单独 Thread 的Service或仅放在 Activity 旁边的另一个 Thread 中。 Never do heavy work, infinte loops, or blocking calls in your main (UI) Thread.切勿在主 (UI) 线程中进行繁重的工作、无限循环或阻塞调用。

If you are using kotlin then you can use coroutines.如果您使用的是 kotlin,那么您可以使用协程。

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4"

initialize a job variable job:Job globally then do:初始化一个工作变量job:Job全局然后做:


job = 
GlobalScope.launch(Dispatchers.Default) {
    while (job.isActive) {
        //do whatever you want
    }
}

Do job.cancel() when you want your loop to stop当您希望循环停止时执行job.cancel()

You need to move the work into another thread (other than the UI thread), to prevent ANR.您需要将工作移至另一个线程(UI 线程除外),以防止出现 ANR。

new Thread( new Runnable(){
        @Override
        public void run(){
            Looper.prepare();
            //do work here
        }
    }).start();

The above is a quick and dirty method, The preferred method in most cases is using AsyncTask以上是一种快速而肮脏的方法,大多数情况下首选方法是使用 AsyncTask

Start an IntentService which will create a background thread for you to run your Service in. Call Looper.prepare() as @YellowJK suggests, but then call Looper.loop() when you need your program to wait for something to happen so the Service isn't killed.启动一个 IntentService ,它将创建一个后台线程供您在其中运行服务。按照@YellowJK 的建议调用 Looper.prepare() ,但是当您需要程序等待某事发生时调用 Looper.loop() 以便服务没有被杀死。

@Override
protected void onHandleIntent(Intent arg0) {
   Looper.prepare();
   //Do work here
   //Once work is done and you are waiting for something such as a Broadcast Receiver or GPS Listenr call Looper.loop() so Service is not killed
   Looper.loop();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM