あなたのサービスで:-
//Receiver that notifies the Service when the phone gets data connection
private NetworkConnectionIntentReceiver netConnReceiver;
次のクラスを作成します:-
/*
* Called in response to a change in network connection - after losing a
* connection to the server, this allows us to wait until we have a usable
* data connection again
*/
class NetworkConnectionIntentReceiver extends BroadcastReceiver
{
private static String TAG ="NetworkConnectionIntentReceiver";
@Override
public void onReceive(Context ctx, Intent intent)
{
// we protect against the phone switching off while we're doing this
// by requesting a wake lock - we request the minimum possible wake
// lock - just enough to keep the CPU running until we've finished
PowerManager pm = (PowerManager) ctx.getSystemService(ctx.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
wl.acquire();
Connection c = Connections.getInstance(ctx).getConnection(clientHandle);
final ActionListener callback = new ActionListener(ctx,
ActionListener.Action.CONNECT, clientHandle,null);
c.getClient().setCallback(new MqttCallbackHandler(ctx, clientHandle,messenger_where_incoming_messages_tobe_sent));
c.getClient().connect(c.getConnectionOptions(), null, callback);
/* The Above Reconnect Logic can be put up in a Reconnect() function.
* OR WRITE Any Other LOGIC TO RECONNECT TO MQTT
*/
// we're finished - if the phone is switched off, it's okay for the CPU
// to sleep now
wl.release();
}
次に、OnResume() または onCreate の適切な場所で次のメソッドを呼び出して、BroadcastReceiver を登録します。
synchronized void handleNetworkChange()
{
// changes to the phone's network - such as bouncing between WiFi
// and mobile data networks - can break the MQTT connection
// the MQTT connectionLost can be a bit slow to notice, so we use
// Android's inbuilt notification system to be informed of
// network changes - so we can reconnect immediately, without
// haing to wait for the MQTT timeout
if (netConnReceiver == null)
{
netConnReceiver = new NetworkConnectionIntentReceiver();
registerReceiver(netConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}