惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
Security Latest
Security Latest
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
Cybersecurity and Infrastructure Security Agency CISA
Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
大猫的无限游戏
大猫的无限游戏
C
CXSECURITY Database RSS Feed - CXSecurity.com
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
C
Cisco Blogs
V
Vulnerabilities – Threatpost
S
Security Archives - TechRepublic
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
J
Java Code Geeks
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Know Your Adversary
Know Your Adversary
博客园 - 叶小钗
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
P
Palo Alto Networks Blog
博客园_首页
V
V2EX
WordPress大学
WordPress大学
Schneier on Security
Schneier on Security
月光博客
月光博客
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
The Cloudflare Blog
罗磊的独立博客
美团技术团队
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Last Week in AI
Last Week in AI
K
Kaspersky official blog
Google Online Security Blog
Google Online Security Blog
S
SegmentFault 最新的问题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog

Lan小站-嗯,不错! - 安卓

android stadio 一直在下载download fastutil-7.2.0.jar - Lan小站-嗯,不错! Android为属性组件动画无效 - Lan小站-嗯,不错! JavaScript调用Android方法,显示Echarts - Lan小站-嗯,不错! Gson解析百度实时热榜Json数据 - Lan小站-嗯,不错! 按照第一行代码使用ToolBar报错。 - Lan小站-嗯,不错! Android webView打开网页 - Lan小站-嗯,不错! Android VideoView播放视频 - Lan小站-嗯,不错! 安卓MPAndroidChart绘制水平柱状图 - Lan小站-嗯,不错! 安卓MPAndroidChart绘制多层级的堆叠条形图 - Lan小站-嗯,不错!
安卓实时获取数据并刷新图表 - Lan小站-嗯,不错!
Lan · 2020-10-30 · via Lan小站-嗯,不错! - 安卓

先来个效果图吧

image.png

然后直接上代码,解说以后有机会我再补上

assets>index.html

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="./js/echarts.min.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="main" style="width: 400px;height:400px;"></div>
    <script type="text/javascript" src="./js/echarts.min.js"></script>
    <script>
        var myChart = echarts.init(document.getElementById('main'));

        function updateData(jsonstr) {
            var shuju = JSON.parse(jsonstr);
            option = {
                xAxis: {
                    type: 'category',
                    data: shuju.data,
                },
                yAxis: {
                    type: 'value'
                },
                series: [{
                    data: shuju.wendu,
                    type: 'line'
                }]
            };
            myChart.setOption(option);
        }
    </script>
</body>

</html>

Mainactivity.java

package cn.lanol.wendu;

import androidx.annotation.NonNull;
import androidx.annotation.UiThread;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

import cn.lanol.wendu.Helper.GetContext;
import cn.lanol.wendu.Helper.SQLiteDBhelper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private SQLiteDBhelper dBhelper = new SQLiteDBhelper(GetContext.getContext(), "DATA", null, 1);
    private SQLiteDatabase db = dBhelper.getReadableDatabase();
    private WebView webView;
    private Handler handler;

    @SuppressLint({"SetJavaScriptEnabled", "HandlerLeak"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化数据库
        new Thread(new Runnable() {
            @Override
            public void run() {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        getWenDuData();
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                }, 0, 60000);
            }
        }).start();
        webView = findViewById(R.id.echartsView);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.loadUrl("file:///android_asset/index.html");
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Log.d("标签", "handleMessage: " + msg.what);
                webView.loadUrl("javascript:updateData('" + getNewData() + "')");
            }
        };
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getNewData() {
        dBhelper.getWritableDatabase();
        String wenduJson = "[";
        String timeJson = "[";
        Cursor a = db.query("WenDu", null, null, null, null, null, "ID desc", "5");
        if (a.moveToFirst()) {
            do {
                String time = a.getString(a.getColumnIndex("time"));
                String wendu = a.getString(a.getColumnIndex("wendu"));
                wenduJson += """ + wendu + "",";
                timeJson += """ + time + "",";
            } while (a.moveToNext());
        }
        timeJson = timeJson.substring(0, timeJson.length() - 1) + ']';
        wenduJson = wenduJson.substring(0, wenduJson.length() - 1) + ']';
        String result = "{"data":" + timeJson + ","wendu":" + wenduJson + "}";
        return result;

    }

    public void getWenDuData() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url("https://api.565.ink/json").get().build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            String res = response.body().string();
            JsonObject a = JsonParser.parseString(res).getAsJsonObject();
            String time = a.get("time").getAsString();
            String wendu = a.get("wendu").getAsString();
            Cursor cursor = db.query("WenDu", null, "time like '%" + time + "%'", null, null, null, null);
            if (cursor.moveToFirst()) {
                Log.d("已存在", time);
            } else {
                ContentValues values = new ContentValues();
                values.put("time", time);
                values.put("wendu", wendu);
                db.insert("WenDu", null, values);
                Log.d("不存在", time);
            }
            Log.d("结果", time + "," + wendu);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:ignore="WebViewLayout">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="温度" />

        <WebView
            android:id="@+id/echartsView"
            android:layout_width="match_parent"
            android:layout_height="400dp" />

    </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start" />
</androidx.drawerlayout.widget.DrawerLayout>

AndroidMainifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="cn.lanol.wendu">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <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:name=".Helper.GetContext"
        tools:ignore="GoogleAppIndexingWarning">
        <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>

SQLiteDBHelper.java

package cn.lanol.wendu.Helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class SQLiteDBhelper extends SQLiteOpenHelper {
    private Context mcontext;
    private static final String CREATE_WENDU = "create table WenDu(id integer primary key autoincrement,time text,wendu integer)";

    public SQLiteDBhelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mcontext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_WENDU);
        Toast.makeText(GetContext.getContext(), "欢迎使用温度实时监控系统", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

GetContext.java

package cn.lanol.wendu.Helper;

import android.app.Application;
import android.content.Context;

public class GetContext extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

目录结构

image.png