1.AndServer简介
官方文档:https://github.com/yanzhenjie/AndServer
AndServer 是一个 HTTP 和反向代理服务器。Android平台的Web服务器和Web框架。它提供了
像SpringMVC一样的注解,如果你熟悉SpringMVC,你可以很快掌握它
2.使用场景
因为公司业务需求,需要在安卓上部署一个单机版的java服务,所以研究了一下这个东西
可以实现服务在Android上运行,实现ip+端口调用接口的功能
3.集成步骤
1.项目build.gradle中添加classpath
apply plugin: 'com.yanzhenjie.andserver'
dependencies {
classpath 'com.yanzhenjie.andserver:plugin:2.1.10'
}
2.初始化
方式一、
public class ServerService extends Service {
private Server server;
@Override
public void onCreate() {
super.onCreate();
server= AndServer.webServer(this)
.port(8080)//服务器端口
.timeout(10, TimeUnit.SECONDS)//连接超时,响应超时时间
.listener(new Server.ServerListener() {
@Override
public void onStarted() {
//需要实现的功能
}
@Override
public void onStopped() {
//需要实现的功能
}
@Override
public void onException(Exception e) {
e.printStackTrace();
}
})
.build();
}
}
方式二、
public class ServerService extends Service {
private Server server;
@Override
public void onCreate() {
super.onCreate();
server= AndServer.webServer(this)
.port(8088)//服务器端口
.timeout(10, TimeUnit.SECONDS)//连接超时,响应超时时间
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
NotificationChannel notificationChannel = new NotificationChannel("my_service", "前台Service通知", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "my_service");
builder.setContentTitle("测试");
builder.setContentText("测试服务器已经启动...");
builder.setSmallIcon(R.drawable.ic_launcher_background);
Notification notification = builder.build();
startForeground(1,notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
server.startup();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
server.shutdown();
}
}
3.在启动类中启动服务
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, ServerService.class));//启动服务
}
}
4.设置AndroidManifest.xml
activity
android:name=".MainActivity"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay"> <!--无页面启动-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".service.ServerService"
android:enabled="true"
android:exported="true"/>
5. 创建接口
@RestController
public class TestController {
@GetMapping(path = "/")
public String index() {
return "欢迎使用本系统!";
}
}