Android中关于长连接的使用

本文详细介绍了如何在Android应用中通过用户解锁行为触发长连接管理,包括广播接收、服务启动与状态检查等关键步骤。
1.首先在AndroidManifest.xml中静态注册用户解锁行为的广播:android.intent.action.USER_PRESENT.
<!-- APP的广播接收器 -->
<receiver android:name=".receiver.AppReceiver">
<span style="white-space:pre">	</span><intent-filter>
<span style="white-space:pre">		</span><action android:name="android.intent.action.USER_PRESENT"/>
<span style="white-space:pre">	</span></intent-filter>
</receiver>

2.用户锁屏解锁后,系统发送广播android.intent.action.USER_PRESENT,然后在AppReceiver.java中接收广播
public class AppReceiver extends BroadcastReceiver {


<span style="white-space:pre">	</span>private static final String TAG = "AppReceiver";

<span style="white-space:pre">	</span>@Override
<span style="white-space:pre">	</span>public void onReceive(Context context, Intent intent) {
<span style="white-space:pre">		</span>String action = intent.getAction();
<span style="white-space:pre">		</span>if (Intent.ACTION_USER_PRESENT.equals(action)) { //手机解锁
<span style="white-space:pre">			</span>// 检查长连接
<span style="white-space:pre">			</span>PushService.actionCheck(context);
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
}

3.在PushService.java中执行一系列动作
	//启动Service
	private static final String ACTION_CHECK = "pushservice.check";
	public static void actionCheck(Context context) {
		Intent intent = new Intent(context, PushService.class);
		intent.setAction(ACTION_CHECK);
		context.startService(intent);
	}
	
	
	//对Service做处理
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null) {	
			String action = intent.getAction();
			if (action  != null) {
				action.equals(ACTION_CHECK) {
					checkPushService();//检查PushService是否运行
				}
			}	
		}
	}

	//检查PushService的几种情况:
    //1.用户锁屏解锁后
    //2.手机网络情况发生改变
    //3.连接断开时
    //4.定时检查
	private void checkPushService() {
		if (pushClient != null && pushClient.isWorking()) {
			Log.d(TAG, "长连接正在运行...");
		} else {
			Log.d(TAG,"长连接断开,需要重新启动");
			startPushService();
		}
	}
	
	//启动长连接
	//启动PushService,总是重启PushClient,不做状态检查,目前在以下几种情况下会调用该方法:
	//1. 系统重启  2. 用户登录  3. 检查PushService状态不正常时
	private void startPushService() {
		Log.d(TAG,"正在启动长连接...");
		
		stopKeepPushServiceAlive();
		
		startKeepPushServiceAlive();
		
		startPushClient(userId);
		
	}
	
	
	//停止计时
	public void stopKeepPushServiceAlive() {
		Log.d(TAG,"stopKeepPushServiceAlive()");
		
		Intent intent = new Intent();
		intent.setClass(PushService.this, PushService.class);
		intent.setAction(ACTION_CHECK);
		PendingIntent pi = PendingIntent.getService(PushService.this, KEEP_ALIVE_ALARM_ID, intent ,PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager alarmMgr = (AlarmManager) PushService.this.getSystemService(ALARM_SERVICE);
		alarmMgr.cancel(pi);
	}
	
	//重新开始计时
	public static final int KEEP_ALIVE_ALARM_ID = 2001;
	
	private static final long KEEP_ALIVE_INTERVAL = 5 * 60 * 1000;
	
	public void startKeepPushServiceAlive() {
		Intent intent = new Intent();
		intent.setClass(PushService.this, PushService.class);
		intent.setAction(ACTION_CHECK);
		PendingIntent pi = PendingIntent.getService(PushService.this, KEEP_ALIVE_ALARM_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		AlarmManager alarmMgr = (AlarmManager) PushService.this.getSystemService(ALARM_SERVICE);
		alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + KEEP_ALIVE_INTERVAL, KEEP_ALIVE_INTERVAL, pi);
	}
	
	
	//private startPushClient(String  userId) {
		if (pushClient != null) {
			pushClient.stopPushService(true);
		}

		if (Utils.isNetworkAvailable(this)) {
			pushClient = new PushClient(userId, 150);
			pushClient.asynStartLoop(this);
			Log.d(TAG, "start push client, userId =" + userId);
		} else {
			Log.d(TAG, "network not available when start push client");
		}
	}
	
	
	//连接成功的通知
	@Override
	public void connectionSuccess() {
		// 拉取新的消息
		Log.d(TAG, "connectionSuccess Thread id = " + Thread.currentThread().getId());
		mHandler.obtainMessage(MSG_CONNECTED_SOCKET).sendToTarget();
	}
	
	//
	private Callback mPushMessageCallback = new Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_CONNECTED_SOCKET:
					onConnected();
					break;
			}
		}
		
	};
	
	//当PushClient连接成功后,清空重试次数,加载新消息.
	private void onConnected() {
		Log.d(TAG, "push service connected");
		this.retries.set(0);

		// 长连接消息的有效时间为5分钟,如果断开时间不到3分钟,不再主动拉取消息
		long now = System.currentTimeMillis();
		if (now - lastConnectedTime < TimeUnit.SECONDS.toMillis(180) ||
				(mLoadingNewMessageTask != null && mLoadingNewMessageTask.getTaskStatus() == Status.RUNNING)) {
			return;
		}

		lastConnectedTime = now;

		pullNewMessageList();
	}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值