很久之前就想做一个车载相关的app、需要实现如下功能:
(1)每0.2秒更新一次当前车辆的最新速度值。
(2)可控制性记录行驶里程。
(3)不连接网络情况下获取当前车辆位置。如(北京市X区X路X号)
(4)实时快速获取车辆运动方向。
(5)获取当前太空卫星数量以及GPS状态。
以上功能不需要连接网络、不需要开蓝牙、APP显示名字等可定制;
条件是有个大屏的Android系统车载导航。
好了、实现上面的第一步是需要一个汽车仪表盘的source、网上搜索了一下是有的,所以直接下载了;详细请点击:
搜索一个然后点击下载即可。 然后用宇宙最骚的eclipse打开。
(1)首先是配置文件如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cgenfei.gz.cn" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- SDCard中创建与删除文件权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 向SDCard写入数据权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/logo" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name=".PGSLActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
1、需要连接网络的权限(<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />)
2、存储卡访问权限(<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />)
代码注释都有的哈、请仔细查看。
(2)页面布局
布局文件代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/speedup" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/bg3" android:orientation="vertical" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="2dp" android:orientation="horizontal" > <honda.Server.SpeedControlView android:id="@+id/speed_control" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </LinearLayout> </LinearLayout>
采用Android开发中的线性布局。
(3)Android源代码
首先需要一个model类进行数据交换读写操作、本人新建的实体如下:
3.1- 实体类:
/* * Project Name:honda * File Name:ModelGPS.java * Package Name:model * Date:2016-8-16下午1:39:56 * Copyright (c) 2016,xxx Rights Reserved. * */ package model; /* * ClassName:ModelGPS * Function: ADD FUNCTION. * Reason: ADD REASON. * Date: 2016-8-16 下午1:39:56 * @author xxxx * @version * @since JDK 1.6 */ public class ModelGPS { public String lng; public String getLng() { return lng; } public double Getlngdouble() { return Double.parseDouble(lng); } public double Getlatdouble() { return Double.parseDouble(lat); } public void setLng(String lng) { this.lng = lng; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getAds() { return ads; } public void setAds(String ads) { this.ads = ads; } public String lat; public String ads; }
3.2- common类:
全部静态变量存储以便其他函数调用该变量值
/* * ClassName:ComcomData * Function: ADD FUNCTION. * Reason: ADD REASON. * Date: 2017-4-16 下午10:59:30 * @author xxx * @version * @since JDK 1.6 */ public class ComData { public static int spdnow = 0;// 当前速度GPS获取 public static String ads = "";// 地址 public static double step = 0.04;// 搜索范围 }
3.3- commonfunction类
公用方法、比如获取点x1到点x2的距离
/* * ClassName:Common * Function: ADD FUNCTION. * Reason: ADD REASON. * Date: 2016-8-12 上午11:33:39 * @author xxx * @version * @since JDK 1.6 */ public class Common { private final double EARTH_RADIUS = 6378.137;// 地球半径 private double rad(double d) { return d * Math.PI / 180.0; } public long Getlongtime() { return new Date().getTime(); } // 计算距离 public double Getdisdb(double lng1, double lat1, double lng2, double lat2) { if (lng1 == 0 || lat1 == 0) return -1; if (lng1 == lng2 && lat1 == lat2) { return 0; } try { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000) / 10000; return s; } catch (Exception e) { return 0; } } // 计算距离 public double Getdis(double lng1, double lat1, double lng2, double lat2) { if (lng1 == lng2 && lat1 == lat2) return 0; try { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000); return s; } catch (Exception e) { return 0; } } public String GetClostADS(ArrayList<ModelGPS> arr, double lng, double lat) { // 没有该地区 if (arr == null) return ""; // 放大范围 if (arr.size() == 0) { ComData.step = ComData.step + 0.01; return ""; } // 缩小范围 if (arr.size() > 3 && ComData.step > 0.02) ComData.step = ComData.step - 0.01; String resut = "", fx = ""; double min = Double.MAX_VALUE; double tem = 0; // 查找相距最近的Point for (int i = 0; i < arr.size(); i++) { tem = Getdis(lng, lat, Double.parseDouble(arr.get(i).getLng()), Double.parseDouble(arr.get(i).getLat())); if (min > tem) { min = tem; resut = arr.get(i).getAds(); fx = null; if (lng > arr.get(i).Getlngdouble()) fx = "东"; else fx = "西"; if (lat < arr.get(i).Getlngdouble()) fx += "南"; else fx += "北"; } } arr = null; return resut + "(" + fx + ")方向" + (min / 10) + "米"; } }
3.4- man.java 主程序代码
该类实现调用各个函数之间的传值以及保存结果、显示在仪表盘上。代码中有日文、、、、不喜欢的请不要喷口水、谢谢。
/* * Project Name:honda * File Name:PGSLActivity.java * Package Name:cgenfei.gz.cn * Date:2016-8-12上午11:33:39 * Copyright (c) 2016, xxx * */ package cgenfei.gz.cn; import java.util.ArrayList; import cgenfei.gz.cn.Common; import model.ModelGPS; import xx.Server.SpeedControlView; import xx.Server.UserService; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Criteria; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; public class PGSLActivity extends Activity { private LocationManager lm; private UserService uService = new UserService(PGSLActivity.this); private Common Common = new Common(); private SpeedControlView speedControlView;// 仪表盘 //刷新状态 public void refresh() { speedControlView.refresh(); } @Override protected void onDestroy() { super.onDestroy(); lm.removeUpdates(locationListener); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 仪表盘 speedControlView = (SpeedControlView) findViewById(R.id.speed_control); new Thread(speedControlView).start(); //GPS lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // 判断GPS是否正常启动 if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { // 返回开启GPS导航设置界面 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent, 0); return; } // 为获取地理位置信息时设置查询条件 String bestProvider = lm.getBestProvider(getCriteria(), true); // 获取位置信息 // 如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER Location location = lm.getLastKnownLocation(bestProvider); updateView(location); // 监听状态 lm.addGpsStatusListener(listener); // 绑定监听,有4个参数 // 参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种 // 参数2,位置信息更新周期,单位毫秒 // 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息 // 参数4,监听 // 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新 // 1秒更新一次,或最小位移变化超过1米更新一次; // 注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(1000);然后执行handler.sendMessage(),更新位置 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 760, 1,locationListener);// 760 } // 位置监听 private LocationListener locationListener = new LocationListener() { /** * 位置信息变化时触发 */ public void onLocationChanged(Location location) { updateView(location); } /** * GPS状态变化时触发 */ public void onStatusChanged(String provider, int status, Bundle extras) { /*switch (status) { // GPS状态为可见时 case LocationProvider.AVAILABLE: //CommonData.ads="現在のGPSのステータスが表示されています"; break; // GPS状态为服务区外时 case LocationProvider.OUT_OF_SERVICE: //CommonData.ads="現在のGPSのステータスが圏外状態であります"; break; // GPS状态为暂停服务时 case LocationProvider.TEMPORARILY_UNAVAILABLE: //CommonData.ads="現在のGPSの状態サスペンド状態"; break; }*/ } /** * GPS开启时触发 */ public void onProviderEnabled(String provider) { Location location = lm.getLastKnownLocation(provider); updateView(location); } /** * GPS禁用时触发 */ public void onProviderDisabled(String provider) { updateView(null); } }; // 状态监听 GpsStatus.Listener listener = new GpsStatus.Listener() { public void onGpsStatusChanged(int event) { }; }; double lnglast = 0, latlast = 0; double lngnow = 0, latnow = 0, speed = 0; long lasttime = Common.Getlongtime(), nowtime = 0; /** * 实时更新文本内容 * * @param location */ private void updateView(Location location) { if (location != null) { lngnow = location.getLongitude(); latnow = location.getLatitude(); speed = location.getSpeed() * 3.6; //没有移动 if (lnglast == lngnow && latnow == latlast) return; // 位置--首先时间5000毫秒控制查询一次 nowtime = Common.Getlongtime(); if (nowtime - lasttime > 6000) { setads(GetADSI()); lasttime = nowtime; } // 速度 if (speed < 3.6) ComData.spdnow = 0; else ComData.spdnow = (int) Math.ceil(speed);// 取上限 refresh(); } } private void setads(String info) { if (info == null || info.equals("")) return; ComData.ads = info + "附近"; } private String GetADSI() { if (lnglast == lngnow && latlast == latnow) return ""; ArrayList<ModelGPS> arrayList = uService.Getads(lngnow, latnow); return Common.GetClostADS(arrayList, lngnow, latnow); } //获取定位设置属性 private Criteria getCriteria() { Criteria criteria = new Criteria(); // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细 criteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置是否要求速度 criteria.setSpeedRequired(true); // 设置是否允许运营商收费 criteria.setCostAllowed(false); // 设置是否需要方位信息 criteria.setBearingRequired(false); // 设置是否需要海拔信息 criteria.setAltitudeRequired(false); // 设置对电源的需求 criteria.setPowerRequirement(Criteria.POWER_LOW); return criteria; } }
3.5 -SpeedControlView.java 绘制仪表盘
根据数学的math.cos sin tan atan 等绘制图形。这个折叠起来!
/* * Project Name:PGSL * File Name:SpeedControlView.java * Package Name:chenfei.Server * Date:2017-4-16下午1:51:19 * Copyright (c) 2017, xx@163.com xx Rights Reserved. * */ package chenfei.Server; /* * ClassName:SpeedControlView * Function: ADD FUNCTION. * Reason: ADD REASON. * Date: 2017-4-16 下午1:51:19 * @author xx * @version * @since JDK 1.6 */ import cgenfei.gz.cn.ComData; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Typeface; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; public class SpeedControlView extends View implements Runnable { private float radius, sRadius; // 圆的半径 private float screenWith, screenHeight;// 屏幕宽高 private float pointX, pointY;// 圆xy坐标 private float baseX, baseY; private Paint mPaint, speedAreaPaint, textPaint; private float textScale; // 速度范围的2个扇形外切矩形 private RectF speedRectF, speedRectFInner; private float mDensitydpi = 0; // 设置速度 并重绘视图 public void refresh() { postInvalidate(); } public SpeedControlView(Context context) { super(context); } public SpeedControlView(Context context, AttributeSet attrs) { super(context, attrs); screenWith = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth(); screenHeight = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight(); DisplayMetrics displayMetrice = getResources().getDisplayMetrics(); screenWith = displayMetrice.widthPixels; screenHeight = displayMetrice.heightPixels; mDensitydpi = (float) displayMetrice.densityDpi / 320; if (mDensitydpi < 1) mDensitydpi = 1; setLayerType(LAYER_TYPE_SOFTWARE, null); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setStrokeWidth(5 * mDensitydpi); textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint.setAntiAlias(true); textPaint.setStyle(Paint.Style.FILL); textPaint.setColor(Color.parseColor("#76EE00")); Typeface typeface = Typeface.createFromAsset(context.getAssets(),"kt.ttf"); textPaint.setTypeface(typeface); radius = screenHeight / 2 - 8; pointX = screenWith / 2; pointY = screenHeight / 2; sRadius = radius - 60 * mDensitydpi; // 设置抗锯齿 speedAreaPaint = new Paint(Paint.ANTI_ALIAS_FLAG); speedAreaPaint.setAntiAlias(true); // 设置画笔样式 speedAreaPaint.setStyle(Paint.Style.FILL); // 设置速度范围扇形的渐变颜色 Shader mShader = new LinearGradient(0, 0, 100, 100, new int[] {0x7001EC9, 0xBF001EC9, 0xFF001EC9 }, null,Shader.TileMode.CLAMP); speedAreaPaint.setShader(mShader); // 初始化速度范围的2个扇形外切矩形 speedRectF = new RectF(pointX - radius + 10 * mDensitydpi, pointY - radius + 10 * mDensitydpi, pointX + radius - 10 * mDensitydpi, pointY + radius - 10 * mDensitydpi); speedRectFInner = new RectF(pointX - radius / 2, pointY - radius / 2, pointX + radius / 2, pointY + radius / 2); } public SpeedControlView(Context context, AttributeSet attrs,int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 绘制速度范围扇形区域 speedAreaPaint.setColor(0x7E3F51B5); drawSpeedArea(canvas); drawSpeedCircle(canvas); drawScale(canvas); for (int i = 0; i < 8; i++) { drawSpeedText(canvas, i * 6); } } // 速度刻度值 private void drawSpeedText(Canvas canvas, int value) { double hudu = 0; textPaint.setTextSize(25 * mDensitydpi); textScale = (int) (textPaint.descent() + textPaint.ascent()) / 2; String TEXT = String.valueOf(value * 5); hudu = (2 * Math.PI / 360) * 6 * (value + 39); baseX = (int) (pointX + Math.sin(hudu) * sRadius - textScale / 2 - textPaint.measureText(TEXT) / 1.5); baseY = (int) (pointY - Math.cos(hudu) * sRadius - textScale / 2); canvas.drawText(TEXT, baseX, baseY, textPaint); } private void drawSpeedCircle(Canvas canvas) { mPaint.setColor(0xFF343434); canvas.drawCircle(pointX, pointY, radius, mPaint); // 外圈2个圆 mPaint.setStrokeWidth(4 * mDensitydpi); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0xBF3F6AB5); canvas.drawCircle(pointX, pointY, radius, mPaint); mPaint.setStrokeWidth(3 * mDensitydpi); canvas.drawCircle(pointX, pointY, radius - 10 * mDensitydpi, mPaint); // 内圈2个圆 mPaint.setStrokeWidth(5 * mDensitydpi); mPaint.setColor(0xE73F51B5); canvas.drawCircle(pointX, pointY, radius / 2, mPaint); mPaint.setColor(0x7E3F51B5); canvas.drawCircle(pointX, pointY, radius / 2 + 5 * mDensitydpi, mPaint); // 速度显示lab textPaint.setTextSize(85 * mDensitydpi); float textWidth = textPaint.measureText(ComData.spdnow + ""); baseX = (int) (pointX - textWidth / 2); baseY = (int) (pointY + Math.abs(textPaint.ascent() + textPaint.descent()) / 4); canvas.drawText(ComData.spdnow + "", baseX, baseY, textPaint); //速度单位lab textPaint.setTextSize(20 * mDensitydpi); textWidth = textPaint.measureText("Km/h"); baseX = (int) (pointX - textWidth / 2); baseY = (int) (pointY + Math.abs(textPaint.ascent()+ textPaint.descent()) / 4); canvas.drawText("Km/h", baseX, baseY + 50 * mDensitydpi, textPaint); //地理位置lab textPaint.setTextSize(20 * mDensitydpi); textWidth = textPaint.measureText(ComData.ads); baseX = (int) (pointX - textWidth / 2); baseY = (int) (pointY * 8 / 5) - 2; canvas.drawText(ComData.ads, baseX, baseY + 50 * mDensitydpi, textPaint); } private void drawScale(Canvas canvas) { for (int i = 0; i < 60; i++) { if (i % 6 == 0) canvas.drawLine(pointX - radius + 10 * mDensitydpi, pointY,pointX - radius + 50 * mDensitydpi, pointY, mPaint); else canvas.drawLine(pointX - radius + 10 * mDensitydpi, pointY,pointX - radius + 30 * mDensitydpi, pointY, mPaint); canvas.rotate(6, pointX, pointY); } } /** * 绘制速度区域扇形 */ private void drawSpeedArea(Canvas canvas) { float degree; if (ComData.spdnow < 210) { degree = (float) (ComData.spdnow * 1.2); } else { degree = 252; } canvas.drawArc(speedRectF, 144, degree, true, speedAreaPaint); mPaint.setStyle(Paint.Style.FILL); //mPaint.setColor(Color.BLACK); canvas.drawArc(speedRectFInner, 144, degree, true, mPaint); mPaint.setStyle(Paint.Style.STROKE); } @Override public void run() { /*while (true) { try { Thread.sleep(40); refresh(); } catch (InterruptedException e) { e.printStackTrace(); } }*/ } }
ok 到了这里应该有一个华丽的分割线了
---------------------------------------------------------------------------------------
以上可以实现仪表盘以及获取GPS等数据的功能了。
下面是要获取该lng lat经纬度所在地名称。
3.6- 抓取XX度的地图经纬度数据。
调用api,然后是这样的获取经纬度
for(lng){ for(lat){ get_xx_api(lng,lat,sign); } }
遍历整个中国大地的经度以及纬度,然后会得到一堆json、解析后存储到db文件中、本人存储的方式是这样的做法。
sql="insert into GPS117(lng,lat,ads) values (117.289,40.65,'北京市密云县Y264')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,40.61,'北京市密云县Y257')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,40.17,'北京市平谷区韩海路')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,40.09,'天津市蓟县砖蓟路')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,40.05,'天津市蓟县S1(津蓟高速)')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,40.01,'天津市蓟县许邦路')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,39.890,'天津市蓟县东毛路')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,39.770,'天津市宝坻区G1(京哈高速)')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,39.730,'天津市宝坻区西关街')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,39.690,'天津市宝坻区开元路')"; db.execSQL(sql); sql="insert into GPS117(lng,lat,ads) values (117.289,39.650,'天津市宝坻区国泰路')"; db.execSQL(sql);
这样的数据很多,获取数据过程中lng和lat的自增因子越小导致代码越多;当然你可以用程序生成、解放双手干其TA的。
有这些代码后就可以在app第一次安装启动时候执行到本地的db中了、是不是很完美呢、解决了不需要网络的大难题。
3.7- DatabaseHelper.java
该类就是程序安装启动时候执行的函数功能类了。
/* * Project Name:PGSL * File Name:DatabaseHelper.java * Package Name:xx.db * Date:2016-8-16下午1:16:07 * Copyright (c) 2016, xx@163.com xx Rights Reserved. * */ package xx.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /* * ClassName:DatabaseHelper * Function: ADD FUNCTION. * Reason: ADD REASON. * Date: 2016-8-16 下午1:16:07 * @author xx * @version * @since JDK 1.6 */ public class DatabaseHelper extends SQLiteOpenHelper { static String name = "xxxxxxxxxxx4dwd6f9w4f4wf4ew5f4ew54f.db"; static int dbVersion = 1; public DatabaseHelper(Context context) { super(context, name, null, dbVersion); } // 只在创建的时候用一次 public void onCreate(SQLiteDatabase db) { CommonTab tab = new CommonTab(); tab.CreateTable(db); tab = null; CommonDBBASE base = new CommonDBBASE(); base.AddDATA(db); // BASE base = null; CommonCNOne one = new CommonCNOne(); one.AddDATA(db); one = null; CommonCNTwo two = new CommonCNTwo(); two.AddDATA(db); two = null; CommonCNThree three = new CommonCNThree(); three.AddDATA(db); three = null; CommonCNF fo = new CommonCNF(); fo.AddDATA(db); fo = null; } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
OK。。。。代码到此结束!
(4)实例图
好了、、、、这是目前本人实现的基于Android系统的车载app。
.
.
.
.
.
.
接下来本人琢磨着使用andrunio做一个类似于某宝上的抬头显示那玩意、、前提是接入汽车预留的接口(一般在方向盘)下面那玩意。
以上!