Pra*_*kar 2 java android mqtt paho
我在我的应用程序中使用Eclipse Paho android mqtt服务.我能够订阅并将消息发布到mqtt broker.我在应用程序中有几个活动,当任何活动开始时,它连接到使用的代理mqttAndroidClient.connect(null, new IMqttActionListener() {}
并获得响应mqttAndroidClient.setCallback(new MqttCallback() {}.
我的问题:
一种"更好"的方法是创建一个Service连接/重新连接到MQTT Broker的方法.
我创建了自己的服务MqttConnectionManagerService,用于维护和管理与代理的连接.
该解决方案的主要特点:
START_STICKY)startService(..)再次调用将触发其onStartCommand()方法(而不是onCreate()).在此方法中,我们只需检查此客户端是否已连接到代理,并在需要时连接/重新连接.示例代码:
MqttConnectionManagerService
public class MqttConnectionManagerService extends Service {
private MqttAndroidClient client;
private MqttConnectOptions options;
@Override
public void onCreate() {
super.onCreate();
options = createMqttConnectOptions();
client = createMqttAndroidClient();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.connect(client, options);
return START_STICKY;
}
private MqttConnectOptions createMqttConnectOptions() {
//create and return options
}
private MqttAndroidClient createMqttAndroidClient() {
//create and return client
}
public void connect(final MqttAndroidClient client, MqttConnectOptions options) {
try {
if (!client.isConnected()) {
IMqttToken token = client.connect(options);
//on successful connection, publish or subscribe as usual
token.setActionCallback(new IMqttActionListener() {..});
client.setCallback(new MqttCallback() {..});
}
} catch (MqttException e) {
//handle e
}
}
}
Run Code Online (Sandbox Code Playgroud)
AndroidManifest.xml中
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="...">
<!-- Permissions required to receive BOOT_COMPLETED event -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!-- activities go here -->
<!-- BroadcastReceiver that starts MqttConnectionManagerService on device boot -->
<receiver android:name=".MqttServiceStartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<!-- Services required for using MQTT -->
<service android:name="org.eclipse.paho.android.service.MqttService" />
<service android:name=".MqttConnectionManagerService" />
</application>
</manifest>
Run Code Online (Sandbox Code Playgroud)
MqttServiceStartReceiver
public class MqttServiceStartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MqttConnectionManagerService.class));
}
}
Run Code Online (Sandbox Code Playgroud)
在你的活动中
onResume()
startService(new Intent(this, MqttConnectionManagerService.class));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4869 次 |
| 最近记录: |