现在 Handler() 被弃用了,我应该使用什么?

huangapple go评论86阅读模式
英文:

What do I use now that Handler() is deprecated?

问题

这段代码中的弃用警告如何修复?或者,还有其他任何处理方式吗?

Handler().postDelayed({
    context?.let {
        //代码
    }
}, 3000)
英文:

How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this?

Handler().postDelayed({
    context?.let {
        //code
    }
}, 3000)

答案1

得分: 663

只有无参数构造函数已被弃用,现在更推荐通过构造函数使用Looper.getMainLooper()方法来指定Looper

在Java中使用

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // 你的代码
    }
}, 3000);

在Kotlin中使用

Handler(Looper.getMainLooper()).postDelayed({
    // 你的代码
}, 3000)

来源:developer.android.com

英文:

Only the parameterless constructor is deprecated, it is now preferred that you specify the Looper in the constructor via the Looper.getMainLooper() method.

Use it for Java

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // Your Code
    }
}, 3000);

Use it for Kotlin

Handler(Looper.getMainLooper()).postDelayed({
    // Your Code
}, 3000)

Source : developer.android.com

答案2

得分: 90

从API级别30开始,有2个已被弃用的构造函数。

Google解释了以下原因。

在Handler构造期间隐式选择一个Looper可能导致操作被默默丢失(如果Handler不希望有新任务并退出),崩溃(如果有时在线程上创建没有活动Looper的Handler),或者竞态条件,其中与Handler关联的线程与作者预期的不同。相反,使用Executor或明确指定Looper,使用Looper#getMainLooper、android.view.View#getHandler或类似的方法。如果需要兼容性的隐式线程本地行为,请使用new Handler(Looper.myLooper(), callback)以便读者清晰明了。

解决方案1: 使用Executor

1. 在主线程中执行代码。

Java

// 创建一个在主线程中执行任务的Executor。
Executor mainExecutor = ContextCompat.getMainExecutor(this);

// 在主线程中执行任务
mainExecutor.execute(new Runnable() {
@Override
public void run() {
// 你的代码逻辑在这里。
}
});

Kotlin

// 创建一个在主线程中执行任务的Executor。
val mainExecutor = ContextCompat.getMainExecutor(this)

// 在主线程中执行任务
mainExecutor.execute {
// 你的代码逻辑在这里。
}

2. 在后台线程中执行代码

Java

// 创建一个在后台线程中执行任务的Executor。
ScheduledExecutorService backgroundExecutor = Executors.newSingleThreadScheduledExecutor();

// 在后台线程中执行任务
backgroundExecutor.execute(new Runnable() {
@Override
public void run() {
// 你的代码逻辑在这里。
}
});

// 在3秒后在后台线程中执行任务。
backgroundExecutor.schedule(new Runnable() {
@Override
public void run() {
// 你的代码逻辑在这里。
}
}, 3, TimeUnit.SECONDS);

Kotlin

// 创建一个在后台线程中执行任务的Executor。
val backgroundExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()

// 在后台线程中执行任务
backgroundExecutor.execute {
// 你的代码逻辑在这里。
}

// 在3秒后在后台线程中执行任务。
backgroundExecutor.schedule({
// 你的代码逻辑在这里。
}, 3, TimeUnit.SECONDS)

注意: 使用完后记得关闭Executor。

backgroundExecutor.shutdown(); // 或 backgroundExecutor.shutdownNow();

3. 在后台线程中执行代码并在主线程上更新UI

Java

// 创建一个在主线程中执行任务的Executor。
Executor mainExecutor = ContextCompat.getMainExecutor(this);

// 创建一个在后台线程中执行任务的Executor。
ScheduledExecutorService backgroundExecutor = Executors.newSingleThreadScheduledExecutor();

// 在后台线程中执行任务
backgroundExecutor.execute(new Runnable() {
@Override
public void run() {
// 你的代码逻辑在这里。

    // 在主线程上更新UI
    mainExecutor.execute(new Runnable() {
        @Override
        public void run() {
            // 你的代码逻辑在这里。
        }
    });
}

});

Kotlin

// 创建一个在主线程中执行任务的Executor。
val mainExecutor: Executor = ContextCompat.getMainExecutor(this)

// 创建一个在后台线程中执行任务的Executor。
val backgroundExecutor = Executors.newSingleThreadScheduledExecutor()

// 在后台线程中执行任务
backgroundExecutor.execute {
// 你的代码逻辑在这里。

// 在主线程上更新UI
mainExecutor.execute {
    // 你的代码逻辑在这里。
}

}

解决方案2: 通过使用以下构造函数之一明确指定一个Looper。

1. 在主线程中执行代码

1.1. 带有Looper的Handler

Java

Handler mainHandler = new Handler(Looper.getMainLooper());

Kotlin

val mainHandler = Handler(Looper.getMainLooper())

1.2 带有Looper和Handler.Callback的Handler

Java

Handler mainHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
// 你的代码逻辑在这里。
return true;
}
});

Kotlin

val mainHandler = Handler(Looper.getMainLooper(), Handler.Callback {
// 你的代码逻辑在这里。
true
})

2. 在后台线程中执行代码

2.1. 带有Looper的Handler

Java

// 创建一个具有Looper的后台线程
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

// 创建一个在后台线程中执行任务的Handler。
Handler backgroundHandler = new Handler(handlerThread.getLooper());

Kotlin

// 创建一个具有Looper的后台线程
val handlerThread = HandlerThread("HandlerThread")
handlerThread.start()

// 创建一个在后台线程中执行任务的Handler。
val backgroundHandler = Handler(handlerThread.looper)

2.2. 带有Looper和Handler.Callback的Handler

Java

// 创建一个具有Looper的后台线程
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

// 创建一个在后台线程中执行任务的Handler。
Handler backgroundHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
// 你的代码逻辑在这里。
return true;
}
});

Kotlin

// 创建一个具有Looper的后台线程
val handlerThread = HandlerThread("HandlerThread")
handlerThread.start()

// 创建一个在后台线程中执行任务的Handler。
val backgroundHandler = Handler(handlerThread.looper, Handler.Callback {
// 你的代码逻辑在这里。
true
})

注意: 使用完后记得释放线程。

handlerThread.quit(); // 或 handlerThread.quitSafely();

3. 在后台线程中执行代码并在主线程上更新UI

Java

// 创建一个在主线程中执行代码的Handler
Handler mainHandler = new Handler(Looper.getMainLooper());

// 创建一个具有Looper的后台线程
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

// 创建一个在后台线程中执行任务的Handler。
Handler backgroundHandler = new Handler

英文:

From API level 30, there are 2 constructors that are deprecated.

Google explains the reason below.

> Implicitly choosing a Looper during
> Handler construction can lead to bugs where operations are silently
> lost (if the Handler is not expecting new tasks and quits), crashes
> (if a handler is sometimes created on a thread without a Looper
> active), or race conditions, where the thread a handler is associated
> with is not what the author anticipated. Instead, use an Executor or
> specify the Looper explicitly, using Looper#getMainLooper, {link
> android.view.View#getHandler}, or similar. If the implicit thread
> local behavior is required for compatibility, use new
> Handler(Looper.myLooper(), callback) to make it clear to readers.

Solution 1: Use an Executor

1. Execute code in the main thread.

Java

// Create an executor that executes tasks in the main thread. 
Executor mainExecutor = ContextCompat.getMainExecutor(this);

// Execute a task in the main thread
mainExecutor.execute(new Runnable() {
    @Override
    public void run() {
        // You code logic goes here.
    }
});

Kotlin

// Create an executor that executes tasks in the main thread.
val mainExecutor = ContextCompat.getMainExecutor(this)

// Execute a task in the main thread
mainExecutor.execute {
    // You code logic goes here.
}

2. Execute code in a background thread

Java

// Create an executor that executes tasks in a background thread.
ScheduledExecutorService backgroundExecutor = Executors.newSingleThreadScheduledExecutor();

// Execute a task in the background thread.
backgroundExecutor.execute(new Runnable() {
    @Override
    public void run() {
        // Your code logic goes here.
    }
});

// Execute a task in the background thread after 3 seconds.
backgroundExecutor.schedule(new Runnable() {
    @Override
    public void run() {
        // Your code logic goes here
    }
}, 3, TimeUnit.SECONDS);

Kotlin

// Create an executor that executes tasks in a background thread.
val backgroundExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()

// Execute a task in the background thread.
backgroundExecutor.execute {
    // Your code logic goes here.
}

// Execute a task in the background thread after 3 seconds.
backgroundExecutor.schedule({
    // Your code logic goes here
}, 3, TimeUnit.SECONDS)

Note: Remember to shut down the executor after using.

backgroundExecutor.shutdown(); // or backgroundExecutor.shutdownNow();

3. Execute code in a background thread and update UI on the main thread.

Java

// Create an executor that executes tasks in the main thread. 
Executor mainExecutor = ContextCompat.getMainExecutor(this);

// Create an executor that executes tasks in a background thread.
ScheduledExecutorService backgroundExecutor = Executors.newSingleThreadScheduledExecutor();

// Execute a task in the background thread.
backgroundExecutor.execute(new Runnable() {
    @Override
    public void run() {
        // Your code logic goes here.
        
        // Update UI on the main thread
        mainExecutor.execute(new Runnable() {
            @Override
            public void run() {
                // You code logic goes here.
            }
        });
    }
});

Kotlin

// Create an executor that executes tasks in the main thread. 
val mainExecutor: Executor = ContextCompat.getMainExecutor(this)

// Create an executor that executes tasks in a background thread.
val backgroundExecutor = Executors.newSingleThreadScheduledExecutor()

// Execute a task in the background thread.
backgroundExecutor.execute {
    // Your code logic goes here.

    // Update UI on the main thread
    mainExecutor.execute {
        // You code logic goes here.
    }
}

Solution 2: Specify a Looper explicitly by using one of the following constructors.

1. Execute code in the main thread

1.1. Handler with a Looper

Java

Handler mainHandler = new Handler(Looper.getMainLooper());

Kotlin

val mainHandler = Handler(Looper.getMainLooper())

1.2 Handler with a Looper and a Handler.Callback

Java

Handler mainHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // Your code logic goes here.
        return true;
    }
});

Kotlin

val mainHandler = Handler(Looper.getMainLooper(), Handler.Callback {
    // Your code logic goes here.
    true
})

2. Execute code in a background thread

2.1. Handler with a Looper

Java

// Create a background thread that has a Looper
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

// Create a handler to execute tasks in the background thread.
Handler backgroundHandler = new Handler(handlerThread.getLooper()); 

Kotlin

// Create a background thread that has a Looper
val handlerThread = HandlerThread("HandlerThread")
handlerThread.start()


// Create a handler to execute tasks in the background thread.
val backgroundHandler = Handler(handlerThread.looper)

2.2. Handler with a Looper and a Handler.Callback

Java

// Create a background thread that has a Looper
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

// Create a handler to execute taks in the background thread.
Handler backgroundHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // Your code logic goes here.
        return true;
    }
});

Kotlin

// Create a background thread that has a Looper
val handlerThread = HandlerThread("HandlerThread")
handlerThread.start()


// Create a handler to execute taks in the background thread.
val backgroundHandler = Handler(handlerThread.looper, Handler.Callback {
    // Your code logic goes here.
    true
})

Note: Remember to release the thread after using.

handlerThread.quit(); // or handlerThread.quitSafely();

3. Execute code in a background thread and update UI on the main thread.

Java

// Create a handler to execute code in the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());

// Create a background thread that has a Looper
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();

// Create a handler to execute in the background thread
Handler backgroundHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // Your code logic goes here.
        
        // Update UI on the main thread.
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                
            }
        });
        
        return true;
    }
});

Kotlin

// Create a handler to execute code in the main thread
val mainHandler = Handler(Looper.getMainLooper())

// Create a background thread that has a Looper
val handlerThread = HandlerThread("HandlerThread")
handlerThread.start()

// Create a handler to execute in the background thread
val backgroundHandler = Handler(handlerThread.looper, Handler.Callback {
    // Your code logic goes here.

    // Update UI on the main thread.
    mainHandler.post {
        
    }
    true
})

答案3

得分: 77

如果您想避免在 Kotlin 中进行空值检查(?!!),可以使用 Looper.getMainLooper(),如果您的 Handler 用于处理与 UI 相关的内容,可以像这样使用:

Handler(Looper.getMainLooper()).postDelayed({
   Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
}, 3000)

注意:如果您正在使用片段,请使用 requireContext(),而不是 this@MainActivity

英文:

If you want to avoid the null check thing in Kotlin (? or !!) you can use Looper.getMainLooper() if your Handler is working with some UI related thing, like this:

Handler(Looper.getMainLooper()).postDelayed({
   Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
}, 3000)

Note: use requireContext() instead of this@MainActivity if you are using fragment.

答案4

得分: 29

已弃用的函数是 Handler 的构造函数。请改用 Handler(Looper.myLooper()).postDelayed(runnable, delay)

英文:

The deprecated function is that constructor for Handler. Use Handler(Looper.myLooper()) .postDelayed(runnable, delay) instead

答案5

得分: 24

请考虑使用协程

scope.launch {
    delay(3000L)
    // 做一些事情
}
英文:

Consider using coroutines

scope.launch {
    delay(3000L)
    // do stuff
}

答案6

得分: 21

使用生命周期范围更加简单。在活动或片段内部。

 lifecycleScope.launch {
     delay(2000)
     // 做你的事情
 }

或者使用处理程序

        Handler(Looper.myLooper()!!)
英文:

Using lifecycle scope this is more easy. Inside activity or fragment.

 lifecycleScope.launch {
     delay(2000)
     // Do your stuff
 }

or use handler

        Handler(Looper.myLooper()!!)

答案7

得分: 18

我有3个解决方案

  1. 显式指定 Looper:

    Handler(Looper.getMainLooper()).postDelayed({
        // 代码
    }, 延迟时间)
    
  2. 隐式线程本地行为:

    Handler(Looper.myLooper()!!).postDelayed({
        // 代码
    }, 延迟时间)
    
  3. 使用 Thread

    Thread({
        try{
            Thread.sleep(3000)
        } catch (e : Exception) {
            throw e
        }
         // 代码
    }).start()
    
英文:

I have 3 solutions:

  1. Specify the Looper explicitly:
    Handler(Looper.getMainLooper()).postDelayed({
        // code
    }, duration)
    
  2. Specify the implicit thread local behavior:
    Handler(Looper.myLooper()!!).postDelayed({
        // code
    }, duration)
    
  3. using Thread:
    Thread({
        try{
            Thread.sleep(3000)
        } catch (e : Exception) {
            throw e
        }
         // code
    }).start()
    

答案8

得分: 12

Handler()Handler(Handler.Callback callback)构造函数已被弃用,因为它们可能导致错误和崩溃。请明确使用Executor或Looper。

对于Java

Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //在这里执行你的操作
   }
}, 1000);
英文:

Handler() and Handler(Handler.Callback callback) constructors are deprecated. Because those can leads to bugs & crashes. Use Executor or Looper explicitly.

For Java

Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //do your work here
   }
}, 1000);

答案9

得分: 10

使用这个

```kotlin
Looper.myLooper()?.let {
    Handler(it).postDelayed({
        //您的代码
    }, 2500)
}

<details>
<summary>英文:</summary>

use this

```kotlin
Looper.myLooper()?.let {
    Handler(it).postDelayed({
        //Your Code
    },2500)
}

答案10

得分: 9

使用 Executor 替代 handler 以获取更多信息 Executor
要实现延迟发布,请使用 ScheduledExecutorService

ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -> {
    public void run() {
        // 做一些事情
    }
};
worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);
英文:

Use Executor instead of handler for more info Executor.<br/>
To achieve post delay use ScheduledExecutorService:

ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = () -&gt; {
    public void run() {
        // Do something
    }
};
worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);

答案11

得分: 7

在处理程序构造函数中提供一个循环器

Handler(Looper.getMainLooper())
英文:

Provide a looper in the Handler Constructor

Handler(Looper.getMainLooper())

答案12

得分: 7

import android.os.Looper
import android.os.Handler

inline fun delay(delay: Long, crossinline completion: () -> Unit) {
    Handler(Looper.getMainLooper()).postDelayed({
        completion()
    }, delay)
}

Example:

delay(1000) {
    view.refreshButton.visibility = View.GONE
}
英文:
import android.os.Looper
import android.os.Handler

inline fun delay(delay: Long, crossinline completion: () -&gt; Unit) {
    Handler(Looper.getMainLooper()).postDelayed({
        completion()
    }, delay)
}

Example:

delay(1000) {
    view.refreshButton.visibility = View.GONE
}

答案13

得分: 4

如果您正在使用变量来处理Handler和Runnable,请按以下方式使用。

private Handler handler;
private Runnable runnable;

handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable = () -> {
    // 在这里执行延迟任务
    handler.postDelayed(runnable, 1000);
}, delay);

此外,您需要在onDestroy()方法中移除回调。

@Override
public void onDestroy() {
    super.onDestroy();
    if (handler != null) {
        handler.removeCallbacks(runnable);
    }
}
英文:

If you are using Variable for Handler and Runnable then use it like this.

private Handler handler;
private Runnable runnable;

handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(runnable = () -&gt; {
        // Do delayed stuff here
         handler.postDelayed(runnable, 1000);
    }, delay);

Also You need to remove callbacks in onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    if (handler != null) {
        handler.removeCallbacks(runnable);
    }
}

答案14

得分: 3

根据文档(https://developer.android.com/reference/android/os/Handler#Handler()):

在 Handler 构造过程中隐式选择 Looper 可能会导致 bug,其中操作会被静默丢失(如果 Handler 不期望新任务并退出),崩溃(如果处理程序有时在没有活动 Looper 的线程上创建),或者出现竞态条件,处理程序关联的线程不是作者预期的线程。相反,使用 Executor 或显式指定 Looper,使用 Looper#getMainLooper、{link android.view.View#getHandler} 或类似方法。如果兼容性需要隐式线程本地行为,则使用 new Handler(Looper.myLooper()) 来使读者清楚明白。

我们应该停止使用没有 Looper 的构造函数,而是应该指定一个 Looper。

英文:

According to the document (https://developer.android.com/reference/android/os/Handler#Handler()):

> Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, {link android.view.View#getHandler}, or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper()) to make it clear to readers.

We should stop using the constructor without a Looper, and specify a Looper instead.

答案15

得分: 3

**协程 Kotlin**

    private val SPLASH_SCREEN_TIME_OUT_CONST: Long = 3000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        GlobalScope.launch {
            delay(SPLASH_SCREEN_TIME_OUT_CONST)
            goToIntro()
        }

    }

    private fun goToIntro(){
        startActivity(Intent(this, IntroActivity::class.java))
        finish()
    }
英文:

Coroutines Kotlin

private val SPLASH_SCREEN_TIME_OUT_CONST: Long = 3000

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_splash)
    window.setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN
    )
    GlobalScope.launch {
        delay(SPLASH_SCREEN_TIME_OUT_CONST)
        goToIntro()
    }

}

private fun goToIntro(){
    startActivity(Intent(this, IntroActivity::class.java))
    finish()
}

答案16

得分: 3

以下是翻译好的内容:

这个结构在 Kotlin 中使用是一个不错的主意

companion object Run {
   fun after(delay: Long, process: () -> Unit) {
      Handler(Looper.getMainLooper()).postDelayed({
          process()
      }, delay)
   }
}

之后调用方式为

Run.after(SPLASH_TIME_OUT) {
   val action = SplashFragmentDirections.actionSplashFragmentToLogin()
   v.findNavController().navigate(action)
}
英文:

It's a good idea use this structure in Kotlin

companion object Run {
   fun after(delay: Long, process: () -&gt; Unit) {
      Handler(Looper.getMainLooper()).postDelayed({
          process()
      }, delay)
   }
}

Later call as

Run.after(SPLASH_TIME_OUT) {
   val action = SplashFragmentDirections.actionSplashFragmentToLogin()
   v.findNavController().navigate(action)
}

答案17

得分: 2

Java答案

我编写了一个方便使用的方法。您可以在您的项目中直接使用这个方法。delayTimeMillis 可以设置为 2000,这意味着此代码将在 2 秒后运行。

private void runJobWithDelay(int delayTimeMillis){
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            //todo: 您可以调用您想要的方法。
        }
    }, delayTimeMillis);
}
英文:

Java Answer

I wrote a method to use easily. You can use this method directly in your project. delayTimeMillis can be 2000, it means that this code will run after 2 seconds.

private void runJobWithDelay(int delayTimeMillis){
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            //todo: you can call your method what you want.
        }
    }, delayTimeMillis);
}

答案18

得分: 1

这是我通常使用的代码:

代码:

Handler(Looper.myLooper() ?: return).postDelayed({
    // 在这里编写你想要的代码
}, 3000)

截图:

现在 Handler() 被弃用了,我应该使用什么?

英文:

I usually use this one

Code:

Handler(Looper.myLooper() ?: return).postDelayed({
           // Code what do you want
        }, 3000)

Screenshot:

现在 Handler() 被弃用了,我应该使用什么?

答案19

得分: 0

"handler()等代码是由Android Studio 4.0.1生成的,当从头开始创建全屏活动(例如)时会生成。我知道我们被鼓励使用Kotlin,我也在使用,但我偶尔会使用示例项目来启发一些想法。
很奇怪的是,当Android Studio实际上生成了代码时,我们却受到了批评。也许逐步检查这些错误并加以修复是一个有益的学术活动,但也许Android Studio可以为我们这些爱好者生成新的干净代码…"

英文:

The handler() etc code is generated by the Android Studio 4.0.1 when a Fullscreen Activity, for example, is created from scratch. I know that we are being encouraged to use Kotlin, which I do, but from time to time I use sample projects to get an idea going.
It seems strange that we are chastised by AS when AS actually generates the code. It might be a useful academic activity to go through the errors and fix them but maybe AS could generate new clean code for us enthusiasts...

答案20

得分: 0

对于Xamarin Android,不需要更改以下部分:

Handler handler;
handler = new Handler();

只需将其修改为:

Handler handler;
handler = new Handler(Looper.MyLooper());

其余的代码保持不变。

英文:

For Xamarin Android, instead of

Handler handler;
handler = new Handler();

just write

Handler handler;
handler = new Handler(Looper.MyLooper());

the rest of the code is fine.

huangapple
  • 本文由 发表于 2020年4月4日 12:58:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/61023968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定