'Android Studio app crash when paho mqtt eclipse client connect [duplicate]

My Android app keeps crashing only in Android 12 when i want to connect to the mqtt server. What can i do.

I tried this solution:Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified But still doesnt work

My MainActivity.java:

package com.example.garagentor;


import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.concurrent.TimeUnit;


public class MainActivity extends AppCompatActivity{

    MqttAndroidClient client;
    Button conn_btn;
    int button_state = 2;
    Button button_1 = null;
    Button button_2 = null;

    public MqttConnectOptions options_mqtt(){
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("mqtt");
        options.setPassword("*******".toCharArray());
        return options;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_1 = (Button)findViewById(R.id.button1);
        button_2 = (Button)findViewById(R.id.button2);

        String clientId = MqttClient.generateClientId();
        client = new MqttAndroidClient(this.getApplicationContext(), "tcp://10.0.2.1:1883",clientId);

        button_1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    state();
                }
                return false;
            }
        });

        button_2.setOnTouchListener(new View.OnTouchListener() {
            private long startTime = 0;
            private long stopTime = 0;
            private long time1 = 0;
            private int state = 0;
            private int state1 = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                String topic = "garagentor/relay";
                String message = "auf";

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    this.startTime = System.currentTimeMillis();
                    state = 2;
                }

                while (state == 2) {
                    this.stopTime = System.currentTimeMillis();
                    time1 = stopTime - startTime;

                    if (time1 > 1000) {
                        Vibrator vx = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            vx.vibrate(VibrationEffect.createOneShot(140, VibrationEffect.DEFAULT_AMPLITUDE));
                        } else {
                            //deprecated in API 26
                            vx.vibrate(140);
                        }
                        state = 1;

                        try {
                            client.publish(topic, message.getBytes(),2,false);

                            try {
                                TimeUnit.MILLISECONDS.sleep(300);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            state();
                        } catch ( MqttException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }
                    return false;
                }

                if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    time1 = 0;
                    startTime=0;
                    stopTime=0;
                    state = 0;
                    state1 = 0;
                }
                return false;
            }
        });


        try {
            IMqttToken token = client.connect(options_mqtt());
            token.setActionCallback(new IMqttActionListener() {

                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    //        setSubscription();
                    connect_button();

                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    connect_button_fail();
                }

            });
        } catch (MqttException e) {
            e.printStackTrace();
        }


    }


    private void setSubscription(){

        try{
            client.subscribe("garagentor/status_sensor",2);
        }catch (MqttException e){
            e.printStackTrace();
        }
    }

    public void conn(){
        try {
            IMqttToken token = client.connect(options_mqtt());
            token.setActionCallback(new IMqttActionListener() {

                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    setSubscription();
                    connect_button();

                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    connect_button_fail();
                }

            });
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }



    public void disconn(){

        try {
            IMqttToken token = client.disconnect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    disconnect_button();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast.makeText(MainActivity.this,"Could not disconnect!!",Toast.LENGTH_LONG).show();
                }

            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    public void connect_button() {
        conn_btn = findViewById(R.id.connBtn);
        conn_btn.setText("Verbunden");
        conn_btn.setBackgroundColor(Color.GREEN);
        button_state = 1;
        state();
    }

    public void connect_button_fail() {
        conn_btn = findViewById(R.id.connBtn);
        conn_btn.setText("Verbindungsfehler");
        conn_btn.setBackgroundColor(Color.RED);
        button_state = 0;
        state();
    }

    public void disconnect_button() {
        conn_btn = findViewById(R.id.connBtn);
        conn_btn.setText("Reconnect");
        conn_btn.setBackgroundColor(Color.RED);
        button_state = 0;
        state();
    }

    public void button1(View v){
        if (button_state == 1) {
        } else if (button_state == 0) {
            conn();
        }
    }



    public void state() {
        String topic = "garagentor/sensor";
        String message = "abfrage";
        final int[] online_state = {0};
        int delay_1 = 0;


        if (delay_1 == 0) {
            try {
                client.publish(topic, message.getBytes(),2,false);
            } catch ( MqttException e) {
                e.printStackTrace();
            }
            delay_1 = 1;
        }


        client.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable cause) {
                disconnect_button();
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                int msg_state = Integer.parseInt(new String(message.getPayload()));

                if (msg_state == 1) {
                    button_2.setText("Offen");
                    button_2.setBackgroundColor(Color.GREEN);
                    online_state[0] = 1;
                } else if (msg_state == 0){
                    button_2.setText("Geschlossen");
                    button_2.setBackgroundColor(Color.RED);
                    online_state[0] = 1;
                }

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }

        });

        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        delay_1 = 0;
        if (online_state[0] == 1) {
        } else if (online_state[0] == 0) {
            button_2.setText("Offline");
            button_2.setBackgroundColor(Color.RED);
        }

    }


}

My Logs:

05/06 14:40:20: Launching 'app' on OnePlus KB2005.
Install successfully finished in 497 ms.
$ adb shell am start -n "com.example.garagentor/com.example.garagentor.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 9627 on device 'oneplus-kb2005-6a9ff7b5'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10638; state: ENABLED
I/oplus.android.OplusFrameworkFactoryImpl: get feature:IOplusAutoResolutionFeature
    getOplusAutoResolutionFeature
I/Quality: LaunchTime2.0: com.example.garagentor createOrUpdateClassLoaderLocked took time: 51
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.garagentor' set to: 'default'
    App is not on the allowlist for updatable production driver.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
    No Network Security Config specified, using platform default
I/Quality: BindApplication: com.example.garagentor
E/mple.garagento: Loaded layer handle (2784358667622489233) for layer /my_product/lib64/libcolorx-loader.so
    Looking for entrypoint ColorX_Check
    Found ColorX_Check for /my_product/lib64/libcolorx-loader.so
    Check failed
I/oplus.android.OplusFrameworkFactoryImpl: Unknow feature:IOplusTextViewRTLUtilForUG
D/ScrollOptimizationHelper: can't find the config file for optimizaiton
    will not debug for debug is false
I/oplus.android.OplusFrameworkFactoryImpl: get feature:IOplusDynamicVsyncFeature
    get feature:IOplusDynamicVsyncFeature
I/oplus.android.OplusFrameworkFactoryImpl: get feature:IOplusDynamicVsyncFeature
W/mple.garagento: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
E/OplusCustomizeRestrictionManager: sInstance is null, start a new sInstance
D/OplusInputMethodUtil: init DEBUG to false, update DEBUG_IME to false
    init DEBUG to false, update DEBUG_IME to false
I/OplusFeatureCache: Milliseconds spent on init(): 12
D/OplusSlideAnimOptHelper: com.example.garagentor scrollEffectOpt enable = false
D/WindowManager: Add to mViews: DecorView@8953bc3[MainActivity],pkg= com.example.garagentor
D/ExtensionsLoader: createInstance(64bit) : createExtendedFactory
E/ExtensionsLoader: dlopen failed: library "libhwuiextimpl.so" not found
D/ExtensionsLoader: createInstance(64bit) : createExtendedFactory
E/ExtensionsLoader: dlopen failed: library "libSchedAssistExtImpl.so" not found
I/Quality: Skipped: false 1
V/OplusZoomWindowDecorViewHelper: setLastReportedMergedConfiguration mZoomDisplayHeight: 2400 getDecorView.143997891
I/AdrenoGLES-0: QUALCOMM build                   : a05eee6955, I893e5129fb
    Build Date                       : 12/15/20
    OpenGL ES Shader Compiler Version: EV031.32.02.06
    Local Branch                     : 
    Remote Branch                    : 
    Remote Branch                    : 
    Reconstruct Branch               : 
    Build Config                     : S P 10.0.7 AArch64
    Driver Path                      : /vendor/lib64/egl/libGLESv2_adreno.so
I/AdrenoGLES-0: PFP: 0x016dd091, ME: 0x00000000
D/hw-ProcessState: Binder ioctl to enable oneway spam detection failed: Invalid argument
D/SurfaceComposerClient: VRR [FRTC] client handle [bufferId:18446744073709551615 framenumber:0] [ffffffff, ffffffff]
I/Choreographer: Skipped 45 frames!  The application may be doing too much work on its main thread.
I/Quality: Skipped: false 45
D/AlarmPingSender: Register alarmreceiver to MqttServiceMqttService.pingSender.paho858786981876928
D/CompatibilityChangeReporter: Compat change id reported: 160794467; UID 10638; state: ENABLED
E/AndroidRuntime: FATAL EXCEPTION: MQTT Rec: paho858786981876928
    Process: com.example.garagentor, PID: 9627
    java.lang.IllegalArgumentException: com.example.garagentor: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:378)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:648)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:635)
        at org.eclipse.paho.android.service.AlarmPingSender.start(AlarmPingSender.java:76)
        at org.eclipse.paho.client.mqttv3.internal.ClientState.connected(ClientState.java:1214)
        at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:1050)
        at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:151)
        at java.lang.Thread.run(Thread.java:920)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source