当前位置:网站首页 > 更多 > 编程开发 > 正文

[安卓] 安卓实时获取数据并刷新图表

作者:CC下载站 日期:2020-10-30 00:00:00 浏览:72 分类:编程开发

先来个效果图吧

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

assets>index.html

<!doctypehtml>
<htmllang="en">

<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0">
<metahttp-equiv="X-UA-Compatible"content="ie=edge">
<scriptsrc="./js/echarts.min.js"></script>
<title>Document</title>
</head>

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

functionupdateData(jsonstr){
varshuju=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

packagecn.lanol.wendu;

importandroidx.annotation.NonNull;
importandroidx.annotation.UiThread;
importandroidx.appcompat.app.AppCompatActivity;

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

importcom.google.gson.Gson;
importcom.google.gson.JsonElement;
importcom.google.gson.JsonObject;
importcom.google.gson.JsonParser;

importjava.io.IOException;
importjava.sql.Time;
importjava.util.Timer;
importjava.util.TimerTask;

importcn.lanol.wendu.Helper.GetContext;
importcn.lanol.wendu.Helper.SQLiteDBhelper;
importokhttp3.OkHttpClient;
importokhttp3.Request;
importokhttp3.Response;

publicclassMainActivityextendsAppCompatActivity{
privateSQLiteDBhelperdBhelper=newSQLiteDBhelper(GetContext.getContext(),"DATA",null,1);
privateSQLiteDatabasedb=dBhelper.getReadableDatabase();
privateWebViewwebView;
privateHandlerhandler;

@SuppressLint({"SetJavaScriptEnabled","HandlerLeak"})
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化数据库
newThread(newRunnable(){
@Override
publicvoidrun(){
Timertimer=newTimer();
timer.schedule(newTimerTask(){
@Override
publicvoidrun(){
getWenDuData();
Messagemsg=newMessage();
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=newHandler(){
@Override
publicvoidhandleMessage(@NonNullMessagemsg){
super.handleMessage(msg);
Log.d("标签","handleMessage:"+msg.what);
webView.loadUrl("javascript:updateData('"+getNewData()+"')");
}
};
try{
Thread.sleep(2000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}

publicStringgetNewData(){
dBhelper.getWritableDatabase();
StringwenduJson="[";
StringtimeJson="[";
Cursora=db.query("WenDu",null,null,null,null,null,"IDdesc","5");
if(a.moveToFirst()){
do{
Stringtime=a.getString(a.getColumnIndex("time"));
Stringwendu=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)+']';
Stringresult="{"data":"+timeJson+","wendu":"+wenduJson+"}";
returnresult;

}

publicvoidgetWenDuData(){
OkHttpClientokHttpClient=newOkHttpClient();
Requestrequest=newRequest.Builder().url("https://api.565.ink/json").get().build();
try{
Responseresponse=okHttpClient.newCall(request).execute();
Stringres=response.body().string();
JsonObjecta=JsonParser.parseString(res).getAsJsonObject();
Stringtime=a.get("time").getAsString();
Stringwendu=a.get("wendu").getAsString();
Cursorcursor=db.query("WenDu",null,"timelike'%"+time+"%'",null,null,null,null);
if(cursor.moveToFirst()){
Log.d("已存在",time);
}else{
ContentValuesvalues=newContentValues();
values.put("time",time);
values.put("wendu",wendu);
db.insert("WenDu",null,values);
Log.d("不存在",time);
}
Log.d("结果",time+","+wendu);
}catch(IOExceptione){
e.printStackTrace();
}
}
}

activity_main.xml

<?xmlversion="1.0"encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayoutxmlns: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

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

<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permissionandroid: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">
<activityandroid:name=".MainActivity">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

</manifest>

SQLiteDBHelper.java

packagecn.lanol.wendu.Helper;

importandroid.content.Context;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.database.sqlite.SQLiteOpenHelper;
importandroid.widget.Toast;

importandroidx.annotation.Nullable;

publicclassSQLiteDBhelperextendsSQLiteOpenHelper{
privateContextmcontext;
privatestaticfinalStringCREATE_WENDU="createtableWenDu(idintegerprimarykeyautoincrement,timetext,wenduinteger)";

publicSQLiteDBhelper(@NullableContextcontext,@NullableStringname,@NullableSQLiteDatabase.CursorFactoryfactory,intversion){
super(context,name,factory,version);
mcontext=context;
}

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

@Override
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){

}
}

GetContext.java

packagecn.lanol.wendu.Helper;

importandroid.app.Application;
importandroid.content.Context;

publicclassGetContextextendsApplication{
privatestaticContextcontext;

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

publicstaticContextgetContext(){
returncontext;
}
}

目录结构

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯