mac
2024-06-21 bf27f4339722c3c00f8600bd3952c74ecafa5fdd
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
package com.hdl.photovoltaic.internet.HttpServer;
 
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
 
import androidx.annotation.Nullable;
 
import com.hdl.photovoltaic.other.HdlLogLogic;
 
import org.w3c.dom.Text;
 
import java.io.IOException;
import java.util.Objects;
 
/**
 * 本地服务器
 */
public class MyNanoHttpService extends Service {
    private MyNanoHttpServer myNanoHttpServer = MyNanoHttpServer.getInstance(null);
 
    private final IBinder mBinder = new LocalBinder();
 
    @Override
    public void onCreate() {
        super.onCreate();
        try {
            myNanoHttpServer.start();
        } catch (Exception e) {
//            if (myNanoHttpServer!=null&&myNanoHttpServer.gserverSocket.isBound() && !serverSocket.isClosed()) {
//                // Port is available
//            } else {
//                // Port is not available
//            }
//            e.printStackTrace();
//            if (!TextUtils.isEmpty(e.getMessage()) && Objects.requireNonNull(e.getMessage()).contains("Address already in use")) {
//                myNanoHttpServer = null;
//                for (int i = MyNanoHttpServer.HTTP_PORT + 1; i < 65535; i++) {
//                    try {
//                        MyNanoHttpServer.HTTP_PORT = i;
//                        myNanoHttpServer = MyNanoHttpServer.getInstance(null);
//                        myNanoHttpServer.start();
//                    } catch (Exception ex) {
//                        String s = ex.getMessage();
//                    }
//                }
//
//            }
            HdlLogLogic.print("初始化Http服务器失败---" + e.getMessage(), true);
            startService(new Intent(this, MyNanoHttpService.class));
        }
    }
 
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
 
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        myNanoHttpServer.stop();
    }
 
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
 
    public class LocalBinder extends Binder {
        public MyNanoHttpService getService() {
            // Return this instance of LocalService so clients can call public methods
            return MyNanoHttpService.this;
        }
    }
}