Android利用Andserver搭建服務(wù)器的詳細(xì)教程
效果

需求
在手機(jī)上有一個(gè)功能,但是需要使用電腦控制什么時(shí)候開始這個(gè)功能,然后上網(wǎng)搜索,找到了AndServer可以滿足要求,我只是實(shí)現(xiàn)了簡(jiǎn)單的功能,如果感興趣的話,可以深入的研究一下。
地址如下:https://github.com/yanzhenjie/AndServer
1.步驟引入
implementation ’com.yanzhenjie:andserver:1.0.2’
2.申請(qǐng)權(quán)限
<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.主要代碼
/** * 監(jiān)聽事件 */ private Server.Listener mListener = new Server.Listener() { @Override public void onStarted() { Log.e(TAG, 'onStarted: '); tvTips.setText('服務(wù)啟動(dòng)成功'); } @Override public void onStopped() { Log.e(TAG, 'onStopped: '); } @Override public void onError(Exception e) { Log.e(TAG, 'onError: ' + e.getMessage()); tvTips.setText('服務(wù)啟動(dòng)失?。?+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); } }
總結(jié)
到此這篇關(guān)于Android利用Andserver搭建服務(wù)器的詳細(xì)教程的文章就介紹到這了,更多相關(guān)android 搭建服務(wù)器內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Android table布局開發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫(kù)使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備