Are there any recommendations for request codes va

2020-02-27 06:48发布

Now I am using random numbers for request codes. So, every time I add new activity for startActivityForResult I need to check all other such activities to avoid collisions. May be there are any practices for defining values, non-collidable by design? What do you think?

标签: android
3条回答
一纸荒年 Trace。
2楼-- · 2020-02-27 07:25

incrementing a number is guaranteed to be collision free (until it wraps). Should actually not happen unless you use a lot of them.

You could add a class to your project that gives you number. For example

public class GlobalStuff {
    private static final AtomicInteger seed = new AtomicInteger();
    public static int getFreshInt() {
        return seed.incrementAndGet();
    }
}

Now in your code, whenever you need to use a number instead of

public void doSomething() {
    startActivityForResult(intentA, 342);
}

do it like

private static final int REQUEST_CODE = GlobalStuff.getFreshInt();
public void doSomething() {
    startActivityForResult(intentA, REQUEST_CODE);
}

and you are safe that you don't use the same number twice. At least while code runs in the same Process.

The only problem is that you can't use those numbers in a switch statement (as in case REQUEST_CODE:) because switch needs numbers that are known at compile-time

查看更多
别忘想泡老子
3楼-- · 2020-02-27 07:33

If you still need to check the result of an activity and like the visually polished structures please check this method.

Declare the internal class inside your activity class:

class RequestCode {
    static final int IMPORT = 100;
    static final int WRITE_PERMISSION = 101;
}

Use a code when starting activity:

startActivityForResult(intent, RequestCode.IMPORT);

Check the result:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RequestCode.IMPORT && resultCode == RESULT_OK) {
        //...
    }
}
查看更多
▲ chillily
4楼-- · 2020-02-27 07:42

Actually you don't need to check all your Activities and it doesn't matter much if you've the same values in different Activities.

The idea for the request codes is that you, in your Activity X, in onActivityResult() can distinguish between the results of different requests you started with startActivityForResult().

So if you have 3 different startActivityForResult() calls in your activity, you'll need 3 different request codes in order to be able to distinguish between them in onActivityResult() - so you can tell which result belongs to which start. But if you have another Activity Y where you're doing something similar, it doesn't matter when the request codes there are the same like in Activity X.

查看更多
登录 后发表回答