Finish android activity from another with Kotlin

2019-03-03 18:48发布

问题:

I'm trying to finish an activity from another (android) with kotlin. I know the wat to do it with java is with the following code (https://stackoverflow.com/a/10379275/7280257)

at the first activity:

BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("finish_activity")) {
            finish();
            // DO WHATEVER YOU WANT.
        }
    }
};
registerReceiver(broadcast_reciever, new IntentFilter("finish_activity"));

On the other activity:

Intent intent = new Intent("finish_activity");
sendBroadcast(intent);

For some reason converting the java activity to kotlin doesn't give a valid output, if someone could give me the correct syntax to do it properly with kotlin I will appreciate it

kotlin output (first activity) [OK]:

val broadcast_reciever = object : BroadcastReceiver() {

    override fun onReceive(arg0: Context, intent: Intent) {
        val action = intent.action
        if (action == "finish_activity") {
            finish()
            // DO WHATEVER YOU WANT.
        }
    }
}
registerReceiver(broadcast_reciever, IntentFilter("finish_activity"))

kotlin output (2nd activity) [OK]

            val intent = Intent("finish_activity")
            sendBroadcast(intent)

ERROR: http://i.imgur.com/qaQ2YHv.png

FIX: THE CODE SHOWN IS RIGHT, YOU JUST NEED TO PLACE IT INSIDE THE onCreate FUNCTION

回答1:

The error Expecting member declaration is there because you wrote a statement (the function call) inside a class. In that scope, declarations (functions, inner classes) are expected.

You have to place your statements inside functions (and then call those from somewhere) in order for them to be executed.