充电桩app代码

SelectCityActivity.java 24KB

    package com.electric.chargingpile.activity; import android.annotation.SuppressLint; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.electric.chargingpile.R; import com.electric.chargingpile.adapter.CityListAdapter; import com.electric.chargingpile.adapter.SearchResultAdapter; import com.electric.chargingpile.data.City; import com.electric.chargingpile.dbhelper.CitySqliteOpenHelper; import com.electric.chargingpile.util.BarColorUtil; import com.electric.chargingpile.util.JsonUtils; import com.electric.chargingpile.util.LoadingDialog; import com.electric.chargingpile.util.PingYinUtil; import com.electric.chargingpile.view.MyLetterView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; //博客地址:http://blog.csdn.net/dmk877/article/details/49757731 public class SelectCityActivity extends Activity implements AMapLocationListener { protected static final String TAG = "MainActivity"; private MyLetterView myLetterView;//自定义的View private TextView tvDialog;//主界面显示字母的TextView private ListView lvCity;//进行城市列表展示 private EditText etSearch; private ListView lvResult;//搜索结果列表展示 private TextView tvNoResult;//搜索无结果时文字展示 private List<City> allCityList;//所有的城市 private List<City> hotCityList;//热门城市列表 private List<City> searchCityList;//搜索城市列表 private List<String> recentCityList;//最近访问城市列表 public static CitySqliteOpenHelper cityOpenHelper;//对保存了最近访问城市的数据库操作的帮助类 public SQLiteDatabase cityDb;//保存最近访问城市的数据库 public CityListAdapter cityListAdapter; public SearchResultAdapter searchResultAdapter; private boolean isScroll = false; private boolean mReady = false; private Handler handler; private OverlayThread overlayThread; //显示首字母对话框 private Socket socket; String date = ""; public static List<City> cityList = new ArrayList<City>(); private AMapLocationClient mlocationClient; private AMapLocationClientOption mLocationOption; private boolean isNeedFresh; public static String currentCity; // 用于保存定位到的城市 public static int locateProcess = 1; // 记录当前定位的状态 正在定位-定位成功-定位失败 LoadingDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_city); BarColorUtil.initStatusBarColor(SelectCityActivity.this); dialog = new LoadingDialog(this); dialog.setCanceledOnTouchOutside(false); setUpMap(); eteCityTime("{\"fun\":\"timer\"}"); dialog.show(); } @Override protected void onStart() { super.onStart(); } private void setAdapter() { cityListAdapter = new CityListAdapter(this, allCityList, hotCityList, recentCityList, this); searchResultAdapter = new SearchResultAdapter(this, searchCityList, this); lvCity.setAdapter(cityListAdapter); Log.e("allCityList===", allCityList.size() + ""); lvResult.setAdapter(searchResultAdapter); } private void initView() { myLetterView = (MyLetterView) findViewById(R.id.my_letterview); tvDialog = (TextView) findViewById(R.id.tv_dialog); myLetterView.setTextView(tvDialog); lvCity = (ListView) findViewById(R.id.lv_city); etSearch = (EditText) findViewById(R.id.et_search); lvResult = (ListView) findViewById(R.id.lv_result); tvNoResult = (TextView) findViewById(R.id.tv_noresult); findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void setListener() { //自定义myLetterView的一个监听 // myLetterView.setOnSlidingListener(new OnSlidingListener() { // // @Override // public void sliding(String s) { // isScroll = false; // if (cityListAdapter.alphaIndexer.get(s) != null) { // //根据MyLetterView滑动到的数据获得ListView应该展示的位置 // int position = cityListAdapter.alphaIndexer.get(s); // //将listView展示到相应的位置 // lvCity.setSelection(position); // } // } // }); etSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString() == null || "".equals(s.toString())) { myLetterView.setVisibility(View.VISIBLE); lvCity.setVisibility(View.VISIBLE); lvResult.setVisibility(View.GONE); tvNoResult.setVisibility(View.GONE); } else { // searchCityList.clear(); myLetterView.setVisibility(View.GONE); lvCity.setVisibility(View.GONE); getResultCityList(s.toString()); if (searchCityList.size() <= 0) { lvResult.setVisibility(View.GONE); tvNoResult.setVisibility(View.VISIBLE); } else { lvResult.setVisibility(View.VISIBLE); tvNoResult.setVisibility(View.GONE); } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); lvCity.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_TOUCH_SCROLL || scrollState == SCROLL_STATE_FLING) { isScroll = true; } } @SuppressLint("DefaultLocale") @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (!isScroll) { return; } if (mReady) { String text; String name = allCityList.get(firstVisibleItem).getCity(); String pinyin = allCityList.get(firstVisibleItem).getPinyin(); if (firstVisibleItem < 4) { text = name; } else { text = PingYinUtil.converterToFirstSpell(pinyin) .substring(0, 1).toUpperCase(); } tvDialog.setText(text); tvDialog.setVisibility(View.VISIBLE); handler.removeCallbacks(overlayThread); // Toast.makeText(MainActivity.this,"测试",0).show(); // 延迟一秒后执行,让中间显示的TextView为不可见 handler.postDelayed(overlayThread, 1000); } } }); } private void initData() { cityOpenHelper = new CitySqliteOpenHelper(SelectCityActivity.this); cityDb = cityOpenHelper.getWritableDatabase(); allCityList = new ArrayList<City>(); hotCityList = new ArrayList<City>(); searchCityList = new ArrayList<City>(); recentCityList = new ArrayList<String>(); handler = new Handler(); overlayThread = new OverlayThread(); } private void initAllCityData() { City city = new City("定位", "0"); // 当前定位城市 allCityList.add(city); city = new City("最近", "1"); allCityList.add(city); city = new City("热门", "2"); allCityList.add(city); city = new City("全部", "3"); allCityList.add(city); allCityList.addAll(getCityList()); } @SuppressWarnings("unchecked") private ArrayList<City> getCityList() { // ArrayList<City>list = new ArrayList<>(); // // if (!date.equals("")){ // Gson g = new Gson(); // list = g.fromJson(date, new TypeToken<List<City>>() { // }.getType()); // } // SQLiteDatabase db; // Cursor cursor = null; // //获取assets目录下的数据库中的所有城市的openHelper // AllCitySqliteOpenHelper op = new AllCitySqliteOpenHelper(MainActivity.this); // ArrayList<City> cityList = new ArrayList<City>(); // try { // op.createDataBase(); // db = op.getWritableDatabase(); // cursor = db.rawQuery("select * from city", null); // // while (cursor.moveToNext()) { // String cityName = cursor.getString(cursor.getColumnIndex("name")); // String cityPinyin = cursor.getString(cursor.getColumnIndex("pinyin")); // City city = new City(cityName, cityPinyin); // cityList.add(city); // } // // } catch (IOException e) { // e.printStackTrace(); // } finally { // cursor.close(); // } Log.e("list===", cityList.size() + ""); if (cityList.size() > 0) { try { Collections.sort(cityList, comparator); } catch (Exception e) { } } // Log.d("getCityList===",cityList.get(0).getCity()); return (ArrayList<City>) cityList; } private void initRecentVisitCityData() { // InsertCity("北京"); // InsertCity("上海"); // InsertCity("广州"); SQLiteDatabase recentVisitDb = cityOpenHelper.getWritableDatabase(); Cursor cursor = recentVisitDb.rawQuery("select * from recentcity order by date desc limit 0, 3", null); while (cursor.moveToNext()) { @SuppressLint("Range") String recentVisitCityName = cursor.getString(cursor.getColumnIndex("name")); recentCityList.add(recentVisitCityName); } cursor.close(); recentVisitDb.close(); } private void initHotCityData() { City city = new City("北京", "2"); hotCityList.add(city); city = new City("上海", "2"); hotCityList.add(city); city = new City("广州", "2"); hotCityList.add(city); city = new City("南京", "2"); hotCityList.add(city); city = new City("合肥", "2"); hotCityList.add(city); city = new City("安徽", "2"); hotCityList.add(city); city = new City("砀山", "2"); hotCityList.add(city); city = new City("日本", "2"); hotCityList.add(city); } /** * 自定义的排序规则,按照A-Z进行排序 */ @SuppressWarnings("rawtypes") Comparator comparator = new Comparator<City>() { @Override public int compare(City lhs, City rhs) { String a = lhs.getPinyin().substring(0, 1); String b = rhs.getPinyin().substring(0, 1); int flag = a.compareTo(b); if (flag == 0) { return a.compareTo(b); } else { return flag; } } }; @SuppressWarnings("unchecked") private void getResultCityList(String keyword) { searchCityList.clear(); // AllCitySqliteOpenHelper dbHelper = new AllCitySqliteOpenHelper(this); // try { // dbHelper.createDataBase(); // SQLiteDatabase db = dbHelper.getWritableDatabase(); // Cursor cursor = db.rawQuery( // "select * from city where name like \"%" + keyword // + "%\" or pinyin like \"%" + keyword + "%\"", null); // City city; // while (cursor.moveToNext()) { // String cityName = cursor.getString(cursor.getColumnIndex("name")); // String cityPinyin = cursor.getString(cursor.getColumnIndex("pinyin")); // city = new City(cityName, cityPinyin); // searchCityList.add(city); // } // cursor.close(); // db.close(); // } catch (IOException e) { // e.printStackTrace(); // } for (int i = 0; i < cityList.size(); i++) { if (cityList.get(i).getCity().contains(keyword) || cityList.get(i).getPinyin().contains(keyword)) { searchCityList.add(cityList.get(i)); } } Log.e("searchCityList==", searchCityList.size() + ""); //将得到的集合按照自定义的comparator的规则进行排序 Collections.sort(searchCityList, comparator); searchResultAdapter.notifyDataSetChanged(); } @Override public void onLocationChanged(AMapLocation amapLocation) { if (amapLocation != null) { if (amapLocation != null && amapLocation.getErrorCode() == 0) { Log.e("000000", "------------"); Log.e("info", "city = " + amapLocation.getCity()); if (!isNeedFresh) { return; } isNeedFresh = false; if (amapLocation.getCity() == null) { locateProcess = 3; // 定位失败 // personList.setAdapter(adapter); // adapter.notifyDataSetChanged(); return; } currentCity = amapLocation.getCity().substring(0, amapLocation.getCity().length() - 1); MainMapActivity.tv_atCity.setText(currentCity); locateProcess = 2; // 定位成功 Log.e(TAG, "onLocationChanged: " + locateProcess); // personList.setAdapter(adapter); // adapter.notifyDataSetChanged(); } else { String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo(); Log.e("AmapErr", errText); } } } // 设置显示字母的TextView为不可见 private class OverlayThread implements Runnable { @Override public void run() { tvDialog.setVisibility(View.INVISIBLE); // overlay.setVisibility(View.INVISIBLE); } } //插入数据到最近访问的城市 public static void InsertCity(String name) { SQLiteDatabase db = cityOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from recentcity where name = '" + name + "'", null); if (cursor.getCount() > 0) { // db.delete("recentcity", "name = ?", new String[]{name}); } db.execSQL("insert into recentcity(name, date) values('" + name + "', " + System.currentTimeMillis() + ")"); db.close(); } @Override protected void onDestroy() { super.onDestroy(); // MyOtto.getInstance().unregister(this); } // @Subscribe // public void main(String s) { // recentCityList.clear(); // initRecentVisitCityData(); // setAdapter(); // } public void eteCityTime(final String params) { new Thread(new Runnable() { @Override public void run() { try { // 创建Socket // socket = new Socket("192.168.1.110",54321); socket = new Socket("cdz.evcharge.cc", 9503); // IP:10.14.114.127,端口54321 // 向服务器发送消息 PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(params); // out.println("{\"fun\":\"getcity\"}"); // 接收来自服务器的消息 BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream())); String msg = br.readLine(); String token = msg; int time = (int) (System.currentTimeMillis() / 1000); // cha = String.valueOf(time - Integer.parseInt(msg)); int cha = time - Integer.parseInt(msg); String Token = getMD5(String.valueOf((System.currentTimeMillis() / 1000 - cha) / 10) + "qwerty"); // String url ="{\"fun\":\"getcity\",\"suit_car2\":" + "\""+"5" + "\"" + ",\"status\":" + "\""+MainApplication.mapStatus + "\"" + ",\"charge_cost_way\":"+"\""+MainApplication.costWay+"\""+",\"belong_attribute\":"+"\""+MainApplication.shuxing+"\""+",\"speed\":"+"\""+MainApplication.sudu+"\""+",\"timer\":" + "\"" + Token + "\"" + "}"; // Log.d("wwwww",url); eteCity("{\"fun\":\"getcity\",\"suit_car2\":" + "\"" + "5" + "\"" + ",\"status\":" + "\"" + "4" + "\"" + ",\"charge_cost_way\":" + "\"" + "" + "\"" + ",\"belong_attribute\":" + "\"" + "" + "\"" + ",\"speed\":" + "\"" + "0" + "\"" + ",\"timer\":" + "\"" + Token + "\"" + "}"); } catch (Exception e) { } } }).start(); } public void eteCity(final String params) { new Thread(new Runnable() { @Override public void run() { try { socket = new Socket("cdz.evcharge.cc", 9503); // IP:10.14.114.127,端口54321 // 向服务器发送消息 PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(params); // out.println("{\"fun\":\"getcity\"}"); // 接收来自服务器的消息 BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream())); String msg = br.readLine(); // Log.d("dddddmsg",msg); if (msg != null) { Message mes = new Message(); mes.obj = msg; mes.what = 4; hand.sendMessage(mes); } // 关闭流 out.close(); br.close(); // 关闭Socket socket.close(); // } } catch (Exception e) { } } }).start(); } //这是请求回来的站点数据 Handler hand = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 4: try { try { date = JsonUtils.getKeyResult(msg.obj.toString(), "data"); // Log.e("data",date); Gson g = new Gson(); List<City> ll = g.fromJson(date, new TypeToken<List<City>>() { }.getType()); // Log.e("city_size==",ll.size()+""); cityList.clear(); if (ll != null && ll.size() > 0) { cityList.addAll(ll); // Log.e("cityList==",cityList.size()+""); initView(); initData(); setListener(); //初始化所有城市列表 initAllCityData(); initRecentVisitCityData();//初始化最近访问的城市数据 initHotCityData();//初始化热门城市 setAdapter();//设置适配器 mReady = true; isNeedFresh = true; dialog.cancel(); } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } break; default: break; } } ; }; public static String getMD5(String content) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(content.getBytes()); return getHashString(digest); } catch (Exception e) { } return null; } private static String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString().toLowerCase(); } private void setUpMap() { // //声明mLocationOption对象 // AMapLocationClientOption mLocationOption = null; try { mlocationClient = new AMapLocationClient(this); //初始化定位参数 mLocationOption = new AMapLocationClientOption(); //设置定位监听 mlocationClient.setLocationListener(this); //设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); mLocationOption.setOnceLocation(true); //设置是否强制刷新WIFI,默认为强制刷新 mLocationOption.setWifiActiveScan(false); //设置定位间隔,单位毫秒,默认为2000ms // mLocationOption.setInterval(2000); //设置定位参数 mlocationClient.setLocationOption(mLocationOption); // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求 // 在定位结束后,在合适的生命周期调用onDestroy()方法 // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除 //启动定位 mlocationClient.startLocation(); } catch (Exception e) { e.printStackTrace(); } } }