Android java->广播接收器的 kotlin 转换失败
Android java->kotlin conversion fails for broadcast receiver
我正在尝试将下面的代码从 Java 转换为 Kotlin。
public class CreateShortcut extends Activity {
class WaitFor extends AsyncTask<Void,Void,Void> {
final int waitPeriod;
private WaitFor (int N) {
this.waitPeriod = N * 1000;
}
@Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(waitPeriod);
Intent bi = new Intent(shortcutId);
bi.putExtra("msg", "deny");
sendBroadcast(bi);
}
catch (InterruptedException ignore) {
}
return null;
}
}
...
这是转换后的 Kotlin。
class CreateShortcut : AppCompatActivity() {
private class WaitFor (N: Int) : AsyncTask<Void, Void, Void>() {
val waitPeriod: Int = N * 1000
override fun doInBackground(vararg voids: Void): Void? {
try {
Thread.sleep(waitPeriod.toLong())
val bi = Intent(shortcutId)
bi.putExtra("msg", "deny")
sendBroadcast(bi)
} catch (ignore: InterruptedException) { /* Ignore */ }
return null
}
}
我的问题是 kotlin 代码中的 sendBroadcast 是未解析的引用。
sendBroadcast 在 Context 中定义,如果我将该行代码修改为:
(this as CreateShortcut).sendBroadcast(bi)
lint 警告 "cast can never succeed"
但代码工作正常。
我已经尝试了一个合格的 this(即 this@CreateShortcut)并且 @CreateShortcut 出现了未解决的问题。同样只是 this.sendBroadcast(intent) 也未解决。
我在网上找到的 Kotlin 广播接收器示例都只使用不合格的 "sendBroadcast" 但它们通常只是从 activity class 中的函数调用而不是从内部调用class 在 activity.
我卡住了。有什么建议吗??
谢谢
史蒂夫·S.
发生这种情况是因为默认情况下,在 Kotlin 中,嵌套 class 是静态的,而在 Java 中则不是。您必须将其限定为 inner
才能重现 Java 代码(非静态)的行为。
在静态嵌套 class 中,您无法访问外部 class.
的非静态成员
private inner class WaitFor (N: Int) : AsyncTask<Void, Void, Void>()
我正在尝试将下面的代码从 Java 转换为 Kotlin。
public class CreateShortcut extends Activity {
class WaitFor extends AsyncTask<Void,Void,Void> {
final int waitPeriod;
private WaitFor (int N) {
this.waitPeriod = N * 1000;
}
@Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(waitPeriod);
Intent bi = new Intent(shortcutId);
bi.putExtra("msg", "deny");
sendBroadcast(bi);
}
catch (InterruptedException ignore) {
}
return null;
}
}
...
这是转换后的 Kotlin。
class CreateShortcut : AppCompatActivity() {
private class WaitFor (N: Int) : AsyncTask<Void, Void, Void>() {
val waitPeriod: Int = N * 1000
override fun doInBackground(vararg voids: Void): Void? {
try {
Thread.sleep(waitPeriod.toLong())
val bi = Intent(shortcutId)
bi.putExtra("msg", "deny")
sendBroadcast(bi)
} catch (ignore: InterruptedException) { /* Ignore */ }
return null
}
}
我的问题是 kotlin 代码中的 sendBroadcast 是未解析的引用。
sendBroadcast 在 Context 中定义,如果我将该行代码修改为:
(this as CreateShortcut).sendBroadcast(bi)
lint 警告 "cast can never succeed" 但代码工作正常。
我已经尝试了一个合格的 this(即 this@CreateShortcut)并且 @CreateShortcut 出现了未解决的问题。同样只是 this.sendBroadcast(intent) 也未解决。
我在网上找到的 Kotlin 广播接收器示例都只使用不合格的 "sendBroadcast" 但它们通常只是从 activity class 中的函数调用而不是从内部调用class 在 activity.
我卡住了。有什么建议吗??
谢谢 史蒂夫·S.
发生这种情况是因为默认情况下,在 Kotlin 中,嵌套 class 是静态的,而在 Java 中则不是。您必须将其限定为 inner
才能重现 Java 代码(非静态)的行为。
在静态嵌套 class 中,您无法访问外部 class.
private inner class WaitFor (N: Int) : AsyncTask<Void, Void, Void>()