Android開(kāi)發(fā)疫情查詢(xún)app(實(shí)例代碼)
一丶工作原理:
App 通過(guò)請(qǐng)求本地tomcat發(fā)布的servlet (調(diào)用了 HttpURLConnection 方法)獲取MySQL數(shù)據(jù)庫(kù)當(dāng)中的數(shù)據(jù),獲取數(shù)據(jù)并返回到App 當(dāng)中,顯示給用戶(hù)。(其中傳遞的格式為 json)
使用的工具:Android Studio 開(kāi)發(fā)APP Eclipse 發(fā)布Servlet,數(shù)據(jù)傳遞
二丶運(yùn)行代碼:
Tomcat 發(fā)布的Servlet 類(lèi):
package com.Servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.Bean.worldbean;import com.Dao.Dao;import com.google.gson.Gson;/** * Servlet implementation class Worldservlet */@WebServlet('/Worldservlet')public class Worldservlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Worldservlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType('text/html;charset=UTF-8'); request.setCharacterEncoding('UTF-8'); String s=null; //獲取傳遞過(guò)來(lái)的參數(shù) String date = request.getParameter('date'); String name =request.getParameter('name'); // Gson 谷歌推出的用于生成和解析JSON 數(shù)據(jù)格式的工具 使用時(shí)需要 導(dǎo)入jar 包 我的是 gson-2.6.2.jar Gson gson=new Gson(); try { worldbean info= Dao.getinfo(date,name); //將數(shù)據(jù) 轉(zhuǎn)換為 Json 格式 s=gson.toJson(info); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(s); //方法作用 只能打印輸出文本格式的(包括html標(biāo)簽) 不可打印對(duì)象 response.getWriter().write(s); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
As 當(dāng)中的MainActivity:
package com.example.yiqingdemo;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import org.json.JSONObject;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class MainActivity extends AppCompatActivity { EditText editTextCountry, editTextDate; TextView textView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextCountry = findViewById(R.id.editText4); editTextDate = findViewById(R.id.editText3); textView = findViewById(R.id.textView2); button = findViewById(R.id.button); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { //本機(jī)tomcat 發(fā)布的網(wǎng)站 其實(shí)是一個(gè)servlet 類(lèi) 必須先讓本機(jī)發(fā)布(啟動(dòng)tomcat 運(yùn)行) 然后才能訪(fǎng)問(wèn)改網(wǎng)站 String url = 'http://192.168.0.106:8080/YiQingSearch/Worldservlet?date=' + editTextDate.getText().toString() + '&name=' + editTextCountry.getText().toString(); get(url); } } ); } public void get(final String url) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; InputStream is = null; try { //獲取url 對(duì)象 URL Url = new URL(url); //獲取httpURlConnection 對(duì)象 connection = (HttpURLConnection) Url.openConnection(); //默認(rèn)為get方法 or post connection.setRequestMethod('GET'); //默認(rèn)不使用緩存 connection.setUseCaches(false); //設(shè)置連接超時(shí)時(shí)間 單位毫秒 connection.setConnectTimeout(10000); //設(shè)置讀取超時(shí)時(shí)間 connection.setReadTimeout(10000); //設(shè)置是否從httpUrlConnection 讀入,默認(rèn)為true connection.setDoInput(true); //相應(yīng)的碼數(shù)為 200 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { //獲取輸入流 is = connection.getInputStream(); //將輸入流內(nèi)的數(shù)據(jù)變?yōu)镾ting類(lèi)型數(shù)據(jù) String info = getStringFromInputStream(is); //轉(zhuǎn)換為JSON 類(lèi)型便于讀取 JSONObject jsonObject = new JSONObject(info); textView.setText( '更新時(shí)間:' + jsonObject.getString('updatetime') + 'n確診人數(shù):' + jsonObject.getString('confirm') + 'n死亡人數(shù):' + jsonObject.getString('dead') + 'n治愈人數(shù):' + jsonObject.getString('heal') ); /* //獲取url 網(wǎng)頁(yè)的源代碼 BufferedReader reader= new BufferedReader(new InputStreamReader(is)); //包裝字節(jié)流為字符流 StringBuilder response = new StringBuilder(); String line; while((line = reader.readLine())!=null){ response.append(line); } String s = response.toString(); */ } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }).start(); } private static String getStringFromInputStream(InputStream is) throws Exception { //定義字節(jié)數(shù)組緩存區(qū) ByteArrayOutputStream by = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len = -1; while ((len = is.read(buff)) != -1) { by.write(buff, 0, len); } is.close(); //將緩沖區(qū)的數(shù)據(jù)轉(zhuǎn)換為 String 類(lèi)型 String html = by.toString(); by.close(); return html; }}
除此之外還需要給APP賦予權(quán)限 :
As 的 AndroidMainfest 如下:
添加注釋的為自主添加的權(quán)限
<?xml version='1.0' encoding='utf-8'?><manifest xmlns:android='http://schemas.android.com/apk/res/android' package='com.example.yiqingdemo'> <uses-permission android:name='android.permission.INTERNET' /> <!--聯(lián)網(wǎng)所需要的權(quán)限--> <uses-permission android:name='android.permission.ACCESS_WIFI_STATE' /> <!-- 主要用于管理 WIFI 連接的各方面--> <uses-permission android:name='android.permission.ACCESS_NETWORK_STATE' /> <!--主要用于監(jiān)視一般網(wǎng)路連接 --> <application android:allowBackup='true' android:icon='@mipmap/ic_launcher' android:label='@string/app_name' android:roundIcon='@mipmap/ic_launcher_round' android:supportsRtl='true' android:theme='@style/AppTheme' android:usesCleartextTraffic='true'> <!-- 指示應(yīng)用程序是否打算使用明文網(wǎng)絡(luò)流量 --> <activity android:name='.MainActivity'> <intent-filter> <action android:name='android.intent.action.MAIN' /> <category android:name='android.intent.category.LAUNCHER' /> </intent-filter> </activity> </application></manifest>
三丶 運(yùn)行結(jié)果:
以上就是Android開(kāi)發(fā)實(shí)例(疫情查詢(xún)app)的詳細(xì)內(nèi)容,更多關(guān)于A(yíng)ndroid開(kāi)發(fā)APP的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 解決Android Studio 格式化 Format代碼快捷鍵問(wèn)題2. php解決注冊(cè)并發(fā)問(wèn)題并提高QPS3. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題4. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)5. Springboot 全局日期格式化處理的實(shí)現(xiàn)6. Java使用Tesseract-Ocr識(shí)別數(shù)字7. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)8. vue實(shí)現(xiàn)web在線(xiàn)聊天功能9. JS原生2048小游戲源碼分享(全網(wǎng)最新)10. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼
