尝试连接到MQTT客户端时应用崩溃

问题描述

当首次启动应用程序并根据需要发送有效负载时,该应用程序将能够启动并连接到MQTT客户端。但是,但是,在30-40分钟后,应用程序将崩溃并发出此错误。当它在服务中执行过多工作时,或者当我最小化应用程序并使其在后台服务中运行时,都会出现此错误。断开连接后,它应该重试连接,但是,它不重试连接,并因此给出错误

任何想法我该如何解决

Error crash

这是我下面的用于连接MQTT的代码

import android.Manifest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.os.Looper;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

.......
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.microsoft.azure.sdk.iot.device.DeviceClient;
import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol;
import com.microsoft.azure.sdk.iot.device.IotHubEventCallback;
import com.microsoft.azure.sdk.iot.device.IotHubMessageResult;
import com.microsoft.azure.sdk.iot.device.IotHubStatusCode;
import com.microsoft.azure.sdk.iot.device.Message;
import com.microsoft.azure.sdk.iot.device.MessageCallback;

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

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MessageService extends Service {

    public static final String TAG = MessageService.class.getSimpleName();

    //things i add
    IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;

    private String mConnectionString;
    private String mdeviceid;
    private int mInterval;

    private Thread mSendThread;
    private DeviceClient mClient;

    private FusedLocationProviderClient mFusedLocationProvider;
    private LocationCallback mLocationCallback;
    private LocationManager locationManager;
    private LocationListener locationListener;

    // flag for GPS status
    boolean isGPSEnabled = false;
    private Vibrator vibration;


    @Override
    public void onCreate() {
        super.onCreate();

         vibration = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        mFusedLocationProvider = LocationServices.getFusedLocationProviderClient(this);
        mLocationCallback = new LocationCallback(){
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                onNewLocation(locationResult.getLastLocation());
                mLastLocation = locationResult.getLastLocation();

            }

        };

    }



    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {

        Intent messageNotificationIntent = new Intent(this,MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,messageNotificationIntent,0);

        Notification messageNotification = new NotificationCompat.Builder(this,Constants.MESSAGE_CHANNEL_ID)
                .setContentTitle("CW Message Service")
                .setContentText("Sending messages")
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentIntent(pendingIntent)
                .build();


        startForeground(1,messageNotification);


        if (intent != null) {
            mdeviceid = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);
            mConnectionString = intent.getStringExtra(Constants.EXTRA_CONNECTION_STRING);
            Constants.setConnectStr(mConnectionString);
            mInterval = intent.getIntExtra(Constants.EXTRA_INTERVAL,60);
            if (Constants.getFalldeviceid().length() == 0) {
                Constants.setFalldeviceid(mdeviceid);
            }

            startService();

        }else{


            stopForeground();
        }

        return START_STICKY_COMPATIBILITY;

    }



    private void stopForeground() {
        // Stop foreground service and remove the notification.
        stopForeground(true);
        stopSelf();
        Toast.makeText(getApplicationContext(),"Softnode Shutting down",Toast.LENGTH_LONG).show();
        vibration.vibrate(200);
    }

    @Override
    public void onDestroy() {
        stopService();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private void startService() {
        Log.i(TAG,"Message Service Started");

        mSendThread = new Thread(() -> {
            try {
                initClient();
                for(; ;)
                {
                    Log.i(TAG,"Client open");

                    sendMessages();
                    Thread.sleep(mInterval);
                }
            } catch (InterruptedException e)
            {
                return;

            } catch(Exception e1){
                Toast.makeText(this,"Error connection lost",Toast.LENGTH_SHORT).show();

                Log.i(TAG,"Exception while opening IoTHub connection: " + e1);
            }
        });
        mSendThread.start();

    }

    private void stopService() {
        new Thread(() -> {
            try {
                mSendThread.interrupt();
                mClient.closeNow();
                Log.i(TAG,"IoT Shutting down...");
            } catch (Exception ignored) {}
        }).start();
    }



    private void initClient() throws URISyntaxException,IOException {

        try {
            mClient = new DeviceClient(mConnectionString,protocol);

            MessageCallback callback = (message,callbackContext) -> {
                Log.i(TAG,"Received message with content: " + new String(message.getBytes(),Message.DEFAULT_IOTHUB_MESSAGE_CHARSET));
                return IotHubMessageResult.COMPLETE;
            };

            mClient.open();
            mClient.setMessageCallback(callback,null);
        }catch (IOException e){

        }
    }

    private void sendMessages() {

        String msgStr = buildMessage();
        try {
            Message sendMessage = new Message(msgStr);
            Log.i(TAG,"Message Sent: " + msgStr);
            EventCallback eventCallback = new EventCallback();
            mClient.sendEventAsync(sendMessage,eventCallback,msgSentCount);

        } catch (Exception e) {
            Log.i(TAG,"Exception while sending event: " + e);
        }
    }

 


    class EventCallback implements IotHubEventCallback {
        public void execute(IotHubStatusCode status,Object context) {
            int i = context instanceof Integer ? (Integer) context : 0;
            Log.i(TAG,("IoT Hub responded to message " + i + " with status " + status.name()));
        }
    }


}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)