lmw
2024-06-16 03172fc2d9a7717f4a9d8de1c5eca3158a550b30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package cn.sinata.rxnetty;
 
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
 
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
 
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import cn.sinata.rxnetty.netStatus.NetChangeObserver;
import cn.sinata.rxnetty.netStatus.NetStateReceiver;
import cn.sinata.rxnetty.netStatus.NetUtils;
import cn.sinata.rxnetty.pipeline.LengthFieldConfigurator;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.channel.ObservableConnection;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
 
/**
 * 长链接基本service。修改为监听器(接口方式)实现。
 */
public class CoreService extends Service {
 
    private WakeLockUtils wakeLockUtils;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
//        wakeLockUtils = new WakeLockUtils(); 常亮
//        wakeLockUtils.acquireWakeLock(this);
        Observable.interval(60, TimeUnit.SECONDS).subscribe(new Subscriber<Long>() {
 
            @Override
            public void onNext(Long aLong) {
                checkState();
            }
 
            @Override
            public void onCompleted() {
 
            }
 
            @Override
            public void onError(Throwable e) {
                Logger.e("netty", "重连功能断开" + e.getLocalizedMessage());
            }
        });
    }
 
    void init() {
        /*
         * 注册发送消息事件监听。
         */
        NettyClient.getInstance().setSendListener(new OnSendListener() {
            @Override
            public void onSend(String s) {
                //先检查通道状态,如果断开,则重连。
                checkState();
                Observable<Void> send = send(s + "\n");
//                Observable<Void> send = send(s);
                Logger.e("netty", "发送消息:"+s);
                if (send != null) {
                    send.subscribe(new Subscriber<Void>() {
                        @Override
                        public void onCompleted() {
                        }
 
                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            checkState();
                            Logger.e("netty", "消息发送失败" + e.getLocalizedMessage());
                        }
 
                        @Override
                        public void onNext(Void aVoid) {
                        }
                    });
                }
            }
        });
        initCheckOb();
    }
 
    public void checkState() {
        if (mConnection == null || mConnection.getChannel() == null
                || !mConnection.getChannel().isActive()
                || !mConnection.getChannel().isWritable()
                || !mConnection.getChannel().isOpen()
                || !mConnection.getChannel().isRegistered()) {
            reConnect();
        }
    }
 
    void initCheckOb() {
        NettyClient.getInstance().setOnCheckListener(new OnCheckListener() {
            @Override
            public void doCheck() {
                checkState();
            }
        });
    }
 
    protected NetChangeObserver mNetChangeObserver = null;
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
 
        init();
 
        NetStateReceiver.registerNetworkStateReceiver(this);
        mNetChangeObserver = new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                super.onNetConnected(type);
                checkState();
            }
            @Override
            public void onNetDisConnect() {
                super.onNetDisConnect();
                Logger.e("netty", "网络断开了");
            }
        };
        NetStateReceiver.registerObserver(mNetChangeObserver);
        if (Config.isStartForeground) {
            startForeground(Config.NOTIFICATION_ID,getNotification());
        }
        return START_NOT_STICKY;
    }
 
    private Notification getNotification(){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //8.0以上创建channel
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                NotificationChannel channel;
                channel = new NotificationChannel("101", "服务", NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true);
                channel.setLightColor(Color.GREEN);
                channel.setShowBadge(true);
                notificationManager.createNotificationChannel(channel);
            }
        }
        Context context = this;
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "101");
        mBuilder.setShowWhen(true);
        mBuilder.setAutoCancel(false);
        int icon = context.getResources().getIdentifier("icon_pt", "mipmap", context.getPackageName());
        mBuilder.setSmallIcon(icon);
        mBuilder.setContentText("正在运行");
        int name = context.getResources().getIdentifier("app_name", "string", context.getPackageName());
        mBuilder.setContentTitle(getString(name));
        String action = getPackageName() + ".ACTION.CLICK";
        Intent intent = new Intent(action);
        intent.setClassName(getPackageName(), getPackageName() + ".broadcast.MBroadcastReceiver");
        PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(contentIntent);
        return mBuilder.build();
    }
 
    private boolean isDestroy = false;
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        if (wakeLockUtils!=null)
            wakeLockUtils.releaseWakeLock();
        NetStateReceiver.unRegisterNetworkStateReceiver(this);
        if (subscriber != null && !subscriber.isUnsubscribed()) {
            subscriber.unsubscribe();
        }
        if (receiveSub != null && !receiveSub.isUnsubscribed()) {
            receiveSub.unsubscribe();
        }
        if (mConnection != null) {
            mConnection.close();
        }
        Logger.e("netty", "service关闭了");
    }
 
    private void connectServer() {
 
        if (NetUtils.isNetworkAvailable(this)) {
            connectionSub();
            connect(Config.SOCKET_SERVER, Config.SOCKET_PORT)
                    .subscribeOn(Schedulers.io())
                    .subscribe(subscriber);
        }
 
    }
 
    private Subscriber<Boolean> subscriber;
 
    private void connectionSub() {
        if (subscriber != null) {
            if (!subscriber.isUnsubscribed()) {
                subscriber.unsubscribe();
            }
            subscriber = null;
        }
        subscriber = new Subscriber<Boolean>() {
            @Override
            public void onCompleted() {
 
            }
 
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                checkState();
                Logger.e("netty", "连接失败" + e.getLocalizedMessage());
            }
 
            @Override
            public void onNext(Boolean aBoolean) {
 
                Observable<ByteBuf> observable = receive();
                if (observable != null) {
                    if (receiveSub == null || receiveSub.isUnsubscribed()) {
                        receiveSub = null;
                        initReceiveOb();
                    }
                    observable.subscribe(receiveSub);
                }
            }
        };
 
    }
 
    private Subscriber<ByteBuf> receiveSub;
 
    private void initReceiveOb() {
        receiveSub = new Subscriber<ByteBuf>() {
            @Override
            public void onCompleted() {
 
            }
 
            @Override
            public void onError(Throwable e) {
                checkState();
                Logger.e("netty", "接收器注册失败" + e.getLocalizedMessage());
            }
 
            @Override
            public void onNext(ByteBuf byteBuf) {
                String s = byteBuf.toString(Charset.forName("utf-8"));
                boolean contains = s.contains("�");
                if (contains) {
                    //乱码了
                    s = byteBuf.toString(Charset.forName("gbk"));
                }
                Logger.e("netty", "收到消息" + s);
                ArrayList<OnMessageListener> listeners = NettyClient.getInstance().getListeners();
                if (listeners != null) {
                    for (OnMessageListener listener : listeners) {
                        if (listener != null) {
                            listener.onMessageReceived(s);
                        }
                    }
                }
            }
        };
    }
 
 
    private void reConnect() {
        Logger.e("netty", "开始重新链接");
        if (isDestroy) {
            Logger.e("netty", "service已经关闭");
            return;
        }
        //reconnect
        Observable.timer(3, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                if (mConnection != null) {
                    mConnection.close();
                    mConnection = null;
                }
                connectServer();
            }
        });
 
    }
 
 
    ObservableConnection<ByteBuf, ByteBuf> mConnection;
 
    public Observable<Boolean> connect(final String url, final int port) {
        return RxNetty.createTcpClient(url, port, new LengthFieldConfigurator())
                .connect()
                .flatMap(new Func1<ObservableConnection<ByteBuf, ByteBuf>, Observable<Boolean>>() {
                    @Override
                    public Observable<Boolean> call(ObservableConnection<ByteBuf, ByteBuf> byteBufByteBufObservableConnection) {
                        mConnection = byteBufByteBufObservableConnection;
                        Logger.e("netty", "连接成功");
                        OnConnectListener listener = NettyClient.getInstance().getConnectListener();
                        if (listener != null) {
                            listener.onConnected();
                        }
                        return Observable.create(new Observable.OnSubscribe<Boolean>() {
                            @Override
                            public void call(Subscriber<? super Boolean> subscriber) {
                                subscriber.onNext(true);
                            }
                        });
                    }
                });
    }
 
    public Observable<ByteBuf> receive() {
        if (mConnection != null) {
            return mConnection.getInput();
        }
        return null;
    }
 
    public Observable<Void> send(String s) {
        if (mConnection != null) {
            return mConnection.writeBytesAndFlush(s.getBytes());
        }
        return null;
    }
}