Search code examples
androidkotlinbroadcastreceiver

Android java->kotlin conversion fails for broadcast receiver


I'm trying to convert the code below from Java to 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;
        }
    }
...

This is the converted 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
        }
    }

My problem is that sendBroadcast in the kotlin code is an unresolved reference.

sendBroadcast is defined in Context and if I modify that line of code to be:

(this as CreateShortcut).sendBroadcast(bi)

The lint warns that the "cast can never succeed" but the code works just fine.

I've tried a qualified this (i.e. this@CreateShortcut) and @CreateShortcut comes up unresolved. Also just this.sendBroadcast(intent) is also unresolved.

The Kotlin broadcast receiver examples I've found online all just use unqualified "sendBroadcast" but they are typically just calling from functions within an activity class and not calling from an inner class in an activity.

I'm stuck. Any suggestions??

Thanks Steve S.


Solution

  • This happens because by default in Kotlin a nested class is static instead in Java it isn't. You have to qualify it as inner to reproduce the behavior of your Java code (non-static). In a static nested class you can't access the non-static members of the outer class.

    private inner class WaitFor (N: Int) : AsyncTask<Void, Void, Void>()