MQTT灭屏下断开连接分析

本文主要分析了MQTT在Android设备灭屏后断开连接的问题,通过导入并调试源码发现,问题可能出在心跳机制的闹钟接收以及comms.checkForActivity方法未回调。在Android 23及以上版本推荐使用setAlarmClock以解决灭屏下心跳问题。最终通过修改源码,使用SystemClock.elapsedRealtimeNanos()来获取时间,解决了因深度休眠导致的时间错误,成功修复了MQTT灭屏断连的故障。
摘要由CSDN通过智能技术生成

    目前在开发过程中遇到过MQTT在手机灭屏后断开连接的问题,但是手机插入usb后不会出现此问题。

    然后我就导入源码进行分析。

    首先,我导入的是org.eclipse.paho.android.service这块源码,在android studio中build.gradle配置的是

 implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

而我要做的是下载org.eclipse.paho.android.service这块源码,然后替换此jar包。

以下service源码路径:https://hub.fastgit.org/eclipse/paho.mqtt.android

下载后导入到APP中,然后对源码进行引用。

include ':app','org.eclipse.paho.android.service'

build.gradle配置

//    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    implementation project(':org.eclipse.paho.android.service')

接着就开始进行源码调试了。

从之前灭屏下断开过程中分析,APP也没主动去断开连接,每次断开都是很有规律的是连接MQTT的1分半左右,而我设置的心跳时间为30秒,刚好3倍,这与之前学习MQTT时发现,如果未进行心跳,则心跳后的三倍时间会主动断开MQTT。

然后就根据源码找到 AlarmPingSender 来对MQTT进行心跳的。

每次在schedule中发起闹钟

	@Override
	public void schedule(long delayInMilliseconds) {
		long nextAlarmInMilliseconds = System.currentTimeMillis()
				+ delayInMilliseconds;
		Log.d(TAG, "Schedule next alarm at " + nextAlarmInMilliseconds);
		AlarmManager alarmManager = (AlarmManager) service
				.getSystemService(Service.ALARM_SERVICE);

        if(Build.VERSION.SDK_INT >= 23){
			// In SDK 23 and above, dosing will prevent setExact, setExactAndAllowWhileIdle will force
			// the device to run this task whilst dosing.
			Log.d(TAG, "Alarm scheule using setExactAndAllowWhileIdle, next: " + delayInMilliseconds);
			alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds,
					pendingIntent);
		} else if (Build.VERSION.SDK_INT >= 19) {
			Log.d(TAG, "Alarm scheule using setExact, delay: " + delayInMilliseconds);
			alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds,
					pendingIntent);
		} else {
			alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds,
					pendingIntent);
		}
	}

这里会根据Android的版本不同去执行的闹钟方式不同,在发送闹钟处和接收闹钟处我都加入了log方便分析。

  @Overr
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值