| | |
| | | |
| | | import android.app.Service; |
| | | import android.content.Intent; |
| | | import android.os.Binder; |
| | | import android.os.IBinder; |
| | | |
| | | import androidx.annotation.Nullable; |
| | | |
| | | /** |
| | | * 本地服务器 |
| | | */ |
| | | public class MyNanoHttpService extends Service { |
| | | private MyNanoHttpServer myNanoHttpServer = MyNanoHttpServer.getInstance(null); |
| | | |
| | | @Nullable |
| | | @Override |
| | | public IBinder onBind(Intent intent) { |
| | | return null; |
| | | } |
| | | private final IBinder mBinder = new LocalBinder(); |
| | | |
| | | @Override |
| | | public void onCreate() { |
| | |
| | | try { |
| | | myNanoHttpServer.start(); |
| | | } catch (Exception e) { |
| | | // if (serverSocket.isBound() && !serverSocket.isClosed()) { |
| | | // // Port is available |
| | | // } else { |
| | | // // Port is not available |
| | | // } |
| | | e.printStackTrace(); |
| | | startService(new Intent(this, MyNanoHttpService.class)); |
| | | } |
| | |
| | | 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; |
| | | } |
| | | } |
| | | } |