startActivityForResult always return 0 when restore sms

后端 未结 1 1394
谎友^
谎友^ 2021-01-16 08:34

This code working properly on lollypop version, But, when i use it on Kitkat, it always returns 0 when i choose \"Yes/No\" option from dialog.

btnSMSRestore.         


        
1条回答
  •  执念已碎
    2021-01-16 09:13

    From the Android documentation:

    onActivityResult Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

    RESULT_CANCELED value is 0, probably on KitKat is not set a result value and the default one is returned.

    As workaround on KitKat, you can try to check if your app is the default one when onActivityResult is fired. Try this code:

    btnSMSRestore.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View arg0) {
            if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                if (!isDefaultSmsApp(SMSActivity.this)) {
                {
                    Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                    intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
                    startActivityForResult(intent, DEF_SMS_REQ);
                }
            } else {
                new RestoreSMS().execute();
            }
    });
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case DEF_SMS_REQ:
                if (Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT && isDefaultSmsApp(this) ||
                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && resultCode == Activity.RESULT_OK) {
                    new RestoreSMS().execute();
                }
                break;
        }
    }
    
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isDefaultSmsApp(Context context) {
        return context.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(context));
    }
    

    0 讨论(0)
提交回复
热议问题