效果
需求
在手机上有一个功能,但是需要使用电脑控制什么时候开始这个功能,然后上网搜索,找到了AndServer可以满足要求,我只是实现了简单的功能,如果感兴趣的话,可以深入的研究一下。
地址如下:https://github.com/yanzhenjie/AndServer
1.步骤引入
implementation 'com.yanzhenjie:andserver:1.0.2'
2.申请权限
<uses-permission android:name="android.permission.INTERNET" />
3.初始化server
private void initServer() { AssetManager assetManager = getAssets(); WebSite webSite = new AssetsWebsite(assetManager, ""); AndServer andServer = new AndServer.Build() .website(webSite) .timeout(30 * 1000) .port(1234) .registerHandler("login", new loginRequest()) .registerHandler("search",new searchRequest()) .listener(mListener) .build(); server = andServer.createServer(); server.start(); }
4.主要代码
/** * 监听事件 */ private Server.Listener mListener = new Server.Listener() { @Override public void onStarted() { Log.e(TAG, "onStarted: "); tvTips.setText("服务启动成功"); } @Override public void onStopped() { Log.e(TAG, "onStopped: "); } @Override public void onError(Exception e) { Log.e(TAG, "onError: " + e.getMessage()); tvTips.setText("服务启动失败:"+e.getMessage()); } }; public class searchRequest implements RequestHandler{ @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "拍照", Toast.LENGTH_SHORT).show(); } }); StringEntity stringEntity = new StringEntity("拍照", "utf-8"); response.setEntity(stringEntity); } } public class loginRequest implements RequestHandler { @Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { Map<String, String> params = HttpRequestParser.parse(request); // Request params. final String userName = params.get("name"); final String password = params.get("pwd"); //中文需要解码 final String userName1 = Uri.decode(userName); final String password1 = Uri.decode(password); Log.e(TAG, "handle: " + userName); runOnUiThread(new Runnable() { @Override public void run() { tvUsername.setText(userName1); tvPwd.setText(password1); } }); StringBuilder sb = new StringBuilder(); sb.append("用户名:" + userName1); sb.append("\n"); sb.append("密码:" + password1); StringEntity stringEntity = new StringEntity(sb.toString(), "utf-8"); response.setEntity(stringEntity); } }