java.lang.RuntimeException:传递结果 ResultInfo{who=@android:requestPermissions:, request=22, result=-1, data=Intent 时出错

java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=22, result=-1, data=Intent

提问人:Daniel Lucena 提问时间:8/20/2023 更新时间:8/20/2023 访问量:66

问:

现在该应用程序正在工作。但它只在第一次启动后(安装后)请求许可。如果我接受权限,应用程序会关闭并出现错误(再次打开应用程序后)应用程序正常打开,但我想避免此错误,但我无法执行此操作。为什么会这样?

以下是我的主要活动代码:

import static android.Manifest.permission.POST_NOTIFICATIONS;
import static com.kifome.cliente.util.Constant.APP_UPDATE_REQUEST_CODE;
import static com.kifome.cliente.util.Constant.BASE_URL;
import static com.kifome.cliente.util.Constant.ID;
import static com.kifome.cliente.util.Constant.UNIQUE_ORDER_ID;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.GeolocationPermissions;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.model.ActivityResult;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.gson.Gson;
import com.kifome.cliente.CustomSwipeToRefresh;
import com.kifome.cliente.R;
import com.kifome.cliente.api.Api;
import com.kifome.cliente.firebase.CreateFirebase;
import com.kifome.cliente.network.RetrofitInstance;
import com.kifome.cliente.util.Constant;
import com.kifome.cliente.util.Funtionality;
import com.kifome.cliente.util.PackageVerificationListener;
import com.kifome.cliente.util.SharePref;
import com.kifome.cliente.web.WebAppInterface;
import com.kifome.cliente.web.webChromeClient.MyWebChromeClient;
import com.kifome.cliente.web.webViewClient.MyWebViewClient;
import com.razorpay.PaymentData;
import com.razorpay.PaymentResultWithDataListener;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements PaymentResultWithDataListener  {

    private static final String TAG = "MainActivity";
    private static Api apiService;
    String Url;
    private WebView myWebView;
    private ProgressBar progressBar;
    private boolean notificationOpened = false;
    public static String mGeolocationOrigin;
    public static GeolocationPermissions.Callback mGeolocationCallback;
    private LocationManager locationManager;
    private CustomSwipeToRefresh swipe;
    private AppUpdateManager mAppUpdateManager;
    private ImageView screen_iv;
    String userAgent ="FoodomaaAndroidWebViewUA";
    private MyWebChromeClient myWebChromeClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{POST_NOTIFICATIONS}, 22);
        }

        SharePref pref = new SharePref(this);

        Log.d(TAG, "Action: " + getIntent().getAction());

        //Check for Update
        CheckUpdate();

        progressBar = findViewById(R.id.progress_circular);
        screen_iv = findViewById(R.id.screen_iv);


//        Log.d(TAG, "COLOR: " + SharePref.getDataFromPref(Constant.STORE_COLOR));
        if (!SharePref.getDataFromPref(Constant.STORE_COLOR).equals("")) {
//            Toast.makeText(this, "Set Color", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.VISIBLE);
            progressBar.getIndeterminateDrawable().setColorFilter(Color.parseColor(SharePref.getDataFromPref(Constant.STORE_COLOR)), PorterDuff.Mode.MULTIPLY);
        }

        //initialize Api Connect with URL
        setupConnection();


        //Connect to firebase
        new CreateFirebase(apiService,this);


        swipe = findViewById(R.id.swipeContainer);
        swipe.setOnRefreshListener(() -> myWebView.reload());

        setWebView();

    }

    private void CheckUpdate() {
        mAppUpdateManager = AppUpdateManagerFactory.create(this);
        mAppUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                    && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                // Request the update.
                try {
                    mAppUpdateManager.startUpdateFlowForResult(
                            appUpdateInfo,
                            AppUpdateType.IMMEDIATE,
                            MainActivity.this,
                            APP_UPDATE_REQUEST_CODE);
                } catch (IntentSender.SendIntentException e) {
                    e.printStackTrace();
                }
                Funtionality.checkAndroidPackage(this, new PackageVerificationListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailure(String message) {
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
                Log.d(TAG, "Update available");
            } else {
                Log.d(TAG, "No Update available");
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mAppUpdateManager
                .getAppUpdateInfo()
                .addOnSuccessListener(
                        appUpdateInfo -> {
                            if (appUpdateInfo.updateAvailability()
                                    == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                                // If an in-app update is already running, resume the update.
                                try {
                                    mAppUpdateManager.startUpdateFlowForResult(
                                            appUpdateInfo,
                                            AppUpdateType.IMMEDIATE,
                                            this,
                                            APP_UPDATE_REQUEST_CODE);
                                } catch (IntentSender.SendIntentException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "ActivityResult");
        if (requestCode == APP_UPDATE_REQUEST_CODE) {
//            Log.d(TAG, "onActivityResult: "+"App REQUEST CODE");
            //when user clicks update button
            if (resultCode == Activity.RESULT_OK) {

            } else if (resultCode == Activity.RESULT_CANCELED) {
                //if user click on close button
                Toast.makeText(this, "Kindly update the app", Toast.LENGTH_LONG).show();
                //Here you can do whatever you want (call finish() to close the app.)
                finish();
            } else if (resultCode == ActivityResult.RESULT_IN_APP_UPDATE_FAILED) {
                Toast.makeText(this, "App download failed.", Toast.LENGTH_LONG).show();
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);
    }

    //Permission request Handle
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Do the stuff that requires permission...
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    //Turn on Gps => fn
                    myWebChromeClient.locationEnabled();
                    //send gps to webview
                }
                mGeolocationCallback.invoke(mGeolocationOrigin, true, false);


            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                mGeolocationCallback.invoke(mGeolocationOrigin, true, false);
                // Should we show an explanation?
            }
        }

    }


    private void setupConnection() {
        BASE_URL = SharePref.getDataFromPref(Constant.ANLIVER_BASE_URL);
        apiService = RetrofitInstance.getRetrofitIntance().create(Api.class);
    }

    private void setWebView() {
        if (!SharePref.getDataFromPref(Constant.STORE_COLOR).equals("")) {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.getIndeterminateDrawable().setColorFilter(Color.parseColor(SharePref.getDataFromPref(Constant.STORE_COLOR)), PorterDuff.Mode.MULTIPLY);
        }


        myWebView =  findViewById(R.id.webChart);

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        myWebView.addJavascriptInterface(new WebAppInterface(this,apiService), "Android");
        webSettings.setUserAgentString(userAgent);
        webSettings.setGeolocationEnabled(true);
        WebView.setWebContentsDebuggingEnabled(true);

        Intent intent = this.getIntent();
        Bundle extras = intent.getExtras();

        if (extras != null) {
            if (extras.containsKey("URL")) {
                Url = extras.getString("URL");
            }
        }

        String link = null;
        if (getIntent().getData() != null) {
            link = getIntent().getData().toString();
        }

        if (Url != null) {
            notificationOpened = true;
            myWebView.loadUrl(Url);
        } else if (link != null) {
            myWebView.loadUrl(link);
        } else {
            myWebView.loadUrl(BASE_URL);
        }


        Animation fade_out = AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out);


        myWebView.setWebViewClient(new MyWebViewClient(this) {

            @Override
            public void onPageFinished(WebView view, String url) {

                screen_iv.startAnimation(fade_out);

                fade_out.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        screen_iv.setVisibility(View.GONE);
                        myWebView.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });

                swipe.setRefreshing(false);

                super.onPageFinished(view, url);
            }

        });



        myWebView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (myWebView.canGoBack()) {
                        myWebView.goBack();
                    } else {
                        finish();
                    }
                    return true;
                }
            }
            return false;
        });


        myWebChromeClient = new MyWebChromeClient(locationManager,this,myWebView,swipe);

        myWebView.setWebChromeClient(myWebChromeClient);



    }

    @Override
    public void onBackPressed() {
        if (notificationOpened) {
            myWebView.loadUrl(BASE_URL);
            notificationOpened = false;
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onPaymentSuccess(String s, PaymentData paymentData) {

        Log.d(TAG, "onPaymentSuccess:  " + s + " Payment Data :" + paymentData);
        // make api call...
        if (ID != null) {
            apiService.sendRazorPayProcess(ID, paymentData.getOrderId(), paymentData.getPaymentId(), paymentData.getSignature())
                    .enqueue(new Callback<Object>() {
                        @Override
                        public void onResponse(Call<Object> call, Response<Object> response) {
                            if (response.isSuccessful()) {
                                String json = new Gson().toJson(response.body());

                                try {
                                    JSONObject jsonObject = new JSONObject(json.trim());
                                    if (jsonObject.getBoolean("success")) {
                                        if (UNIQUE_ORDER_ID != null)
                                            myWebView.loadUrl(BASE_URL.concat("running-order/").concat(UNIQUE_ORDER_ID));
                                        else
                                            myWebView.loadUrl(BASE_URL +"my-orders");

                                    }else{
                                        myWebView.loadUrl(BASE_URL +"my-orders");
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<Object> call, Throwable t) {

                        }
                    });
            if (Build.VERSION.SDK_INT >= 33) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY)  == PackageManager.PERMISSION_GRANTED)
                    return;
                ActivityResultLauncher<String> launcher = registerForActivityResult(
                        new ActivityResultContracts.RequestPermission(), isGranted -> {

                        }
                );
                launcher.launch(android.Manifest.permission.POST_NOTIFICATIONS);
            }
            ActivityResultLauncher<String> requestPermissionLauncher =
                    registerForActivityResult(new ActivityResultContracts.RequestPermission(),
                            isGranted -> {
                                if (isGranted) {
                                    // Permission is granted. Continue the action or workflow in your
                                    Object app;

                                } else {
                                    // Explain to the user that the feature is unavailable because the
                                    // feature requires a permission that the user has denied. At the
                                    // same time, respect the user's decision. Don't link to system
                                    // settings in an effort to convince the user to change their
                                    // decision.
                                }
                            });
        }
    }

    @Override
    public void onPaymentError(int i, String s, PaymentData paymentData) {
        Log.d(TAG, "onPaymentError:  " + s + " Payment Data :" + paymentData);
        myWebView.loadUrl(BASE_URL + "my-orders");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}

以下是我在应用程序中遇到的错误:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=22, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.kifome.cliente/com.kifome.cliente.ui.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void android.webkit.GeolocationPermissions$Callback.invoke(java.lang.String, boolean, boolean)' on a null object reference
    at android.app.ActivityThread.deliverResults(ActivityThread.java:5538)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:5577)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:67)
    at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2394)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:211)
    at android.os.Looper.loop(Looper.java:300)
    at android.app.ActivityThread.main(ActivityThread.java:8296)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:559)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:954)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void android.webkit.GeolocationPermissions$Callback.invoke(java.lang.String, boolean, boolean)' on a null object reference
    at com.kifome.cliente.ui.MainActivity.onRequestPermissionsResult(MainActivity.java:234)
    at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:9058)
    at android.app.Activity.dispatchActivityResult(Activity.java:8912)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:5531)
    ... 13 more
指针 异常 null android-permissions

评论


答: 暂无答案