編輯:關於Android編程
實現該通信的基本思路是:利用servlet服務器進行數據轉發,利用android設備(手機)長連接本文已定時器來模擬長連接,實現了兩部android手機內網通信。
1、作為終端的設備的設備主要是一個開機啟動後就啟動的一個服務,按照一定的時間間隔用http協議去請求服務器,查詢服務器的狀態,如果連接服務器,獲得的相應是開啟GPS信息收集,則在這個服務裡開啟已經安裝在該android手機上的GPS信息收集APP,然後通過Http的GET方式源源不斷的向服務器傳遞GPS信息。
關鍵代碼如下:
public class RunningServiceByPowerOn extends Service { private SharedPreferences mPreferences; public RunningServiceByPowerOn() { // TODO Auto-generated constructor stub } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mPreferences=getSharedPreferences("Config",MODE_PRIVATE); timerTaskforGpsSwitch(); } /** * 每隔5s查詢一次 */ private void timerTaskforGpsSwitch(){ Timer timer = new Timer(); Date d2 = new Date(System.currentTimeMillis()); timer.schedule(new TimerTask() { @Override public void run() { Log.i("是否開啟GPS收集","定時器開啟"); String spec="http://"+ConentValues.serverIp+":8080/MyServer/StartAction?mAction=find_gps_switcher1"; URL url; String str=null; try { url = new URL(spec); str=HttpToServierUtils.connect(url); if(str!=null&&str.equals("GPS_start")){ //開啟GPS服務 Log.i("是否開啟GPS收集","開啟GPS信息收集服務"); //Toast.makeText(getApplicationContext(),"開啟GPS信息收集服務",0).show(); //開啟一個應用 if(mPreferences.getBoolean("isStop", true)){ Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_LAUNCHER); ComponentName cn = new ComponentName("com.yqq.gpsinfolocationstartreceiver", "com.yqq.gpsinfolocationstartreceiver.MainActivity"); intent.setComponent(cn); startActivity(intent); mPreferences.edit().putBoolean("isStop", false).commit(); } } if(str!=null&&str.equals("GPS_stop")){ mPreferences.edit().putBoolean("isStop",true).commit(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } },d2, 5000); } }
public class GpsInfoCollectionService extends Service { private Boolean D=true; private GPSinfoDao mGpSinfoDao; private LocationManager mLocationManager; private Location mLocation; Criteria criteria; private String provider; public GpsInfoCollectionService() { } @Override public IBinder onBind(Intent intent) { if(D){ Log.i("GPS服務數據收集","IBinder()"); } return null; } @Override public void onCreate() { if(D){ Log.i("GPS服務數據收集","onCreate()"); } super.onCreate(); mLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE); criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE);//獲取精確的位置. criteria.setAltitudeRequired(true); criteria.setBearingRequired(true); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setSpeedRequired(true); //判斷GPS是否正常啟動 if(!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ Toast.makeText(this, "請開啟GPS導航...", Toast.LENGTH_SHORT).show(); //返回開啟GPS導航設置界面 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } mGpSinfoDao=new GPSinfoDao(getApplicationContext()); timerTaskforGpsSwitch(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(D){ Log.i("GPS服務數據收集","onStartCommand()"); } provider = mLocationManager.getBestProvider(criteria, true); Log.i("<<<<",provider); mLocationManager.requestLocationUpdates(provider, 300, 0.01f, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { if(location==null){ return; } //updateLocation(location); mLocation=location; new AsyncTask() { private String str=null; @Override protected Void doInBackground(Void... params) { String height=mLocation.getAltitude()+""; String longitude=mLocation.getLongitude()+""; String latitude=mLocation.getLatitude()+""; String name="Test"; //http://172.22.122.1:8080/MyServer/MyTest?longitude=111&latitude=222&height=1000&name=Test //通過http向服務器傳遞數據 String spec="http://"+ConentValues.serverIp+":8080/MyServer/MyTest?longitude="+longitude+"&latitude="+latitude+"&height="+height+"&name="+name; URL url; try { url = new URL(spec); str=HttpToServierUtils.connect(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*GpsInfo info=new GpsInfo(); info.setLongitude(longitude+""); info.setLatitude(latitude+""); info.setHeight(height+""); mGpSinfoDao.addGpsInfo(info); info=null;*/ return null; } @Override protected void onPostExecute(Void result) { Toast.makeText(getApplicationContext(), str,0).show(); }; }.execute(); } }); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { if(D){ Log.i("GPS服務數據收集","onDestroy()"); } mGpSinfoDao=null; mLocationManager=null; mLocation=null; super.onDestroy(); } /** * 每隔5s查詢一次 */ private void timerTaskforGpsSwitch(){ Timer timer = new Timer(); Date d2 = new Date(System.currentTimeMillis()); timer.schedule(new TimerTask() { @Override public void run() { Log.i("終端信息收集","定時器開啟"); String spec="http://"+ConentValues.serverIp+":8080/MyServer/MyTest?mAction=find_gps_switcher"; URL url; String str=null; try { url = new URL(spec); str=HttpToServierUtils.connect(url); /* if(str!=null&&str.equals("GPS_start")){ //開啟GPS服務 Log.i("終端信息收集","開啟GPS信息收集服務"); //Toast.makeText(getApplicationContext(),"開啟GPS信息收集服務",0).show(); }*/ if(str!=null&&str.equals("GPS_stop")){ Log.i("終端信息收集","停止GPS信息收集服務"); //Toast.makeText(getApplicationContext(),"關閉GPS信息收集服務",0).show(); //關閉GPS服務 //getSharedPreferences("Config",MODE_PRIVATE).edit().putBoolean("isStarted", false).commit(); stopSelf(); System.exit(0); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } },d2, 5000); } }
關鍵代碼:
(1)處理GPS信息上傳到服務器的servlet
public class MyTest extends HttpServlet { //private Listinfos; private GpsInfo info; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); resp.setCharacterEncoding("utf-8"); PrintWriter out=resp.getWriter(); String nameAction=(String)req.getAttribute("nameAction"); //String spec="http://"+ConentValues.serverIp+":8080/MyServer/MyTest?longitude="+longitude+"&latitude="+latitude+"&height="+height; String longitude=req.getParameter("longitude"); String latitude=req.getParameter("latitude"); String height=req.getParameter("height"); String name=req.getParameter("name"); String mAction=req.getParameter("mAction"); //查詢服務器端數據庫並獲得返回值 if(mAction!=null&&mAction.equals("find_gps_switcher")){ System.out.println("定時器服務查詢:"+mAction); try { String result=DbUtis.getGPSStaus(); if(result!=null&&result.equals("start_gps")){ out.write("GPS_start"); out.flush(); } if(result!=null&&result.equals("end_gps")){ out.write("GPS_stop"); out.flush(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { //上傳的服務器的數據 if(longitude!=null&&latitude!=null&&height!=null){ info=new GpsInfo(); info.setLongitude(longitude); info.setLatitude(latitude); info.setHeight(height); info.setName(name); DbUtis.insertGpsInfos(info); System.out.println("游客終端上傳的數據:"+info.toString()); out.write("GPS數據已經上傳到服務器"); out.flush(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ /*if(out!=null){ out.close(); }*/ } } }
/** * 處理gps開關信息的servlet * @author yqq_coder * */ public class GpsOnOffAction extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //開啟GPS收集 String gpsSend=req.getParameter("namegpsend"); //關閉GPS終端收集服務 String gpsstop=req.getParameter("namegpsstop"); PrintWriter out=resp.getWriter(); //開啟GPS收集 if(gpsSend!=null&&gpsSend.equals("start_gps")){ System.out.println("GPS信息收集指令:"+gpsSend); out.write("終端GPS信息收集開啟"); try { DbUtis.deleteGpsSatus(); DbUtis.insertGpsSatus("start_gps"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // req.setAttribute("nameAction", "GPS_start"); // req.getRequestDispatcher("/MyTest").forward(req, resp); }else //關閉GPS終端收集服務 if(gpsstop!=null&&gpsstop.equals("end_gps")){ System.out.println("GPS信息關閉指令:"+gpsstop); out.write("終端GPS信息收集關閉"); try { DbUtis.deleteGpsSatus(); DbUtis.insertGpsSatus("end_gps"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //req.setAttribute("nameAction", "GPS_stop"); //req.getRequestDispatcher("/MyTest").forward(req, resp); } out.flush(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.service(req, resp); } }
/** * 查詢GPS信息 * @author yqq_coder * */ public class QurAction extends HttpServlet { private JSONArray infos; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //軌跡顯示參數 String s = req.getParameter("namereq"); PrintWriter out=resp.getWriter(); //查詢 //http://172.22.122.1:8080/MyServer/MyTest?namereq=Test if(s!=null){ out=resp.getWriter(); System.out.println(s); try { infos=DbUtis.getData(s); System.out.println("返回客戶端的數據:"+infos.toString()); out.write(infos.toString()); out.flush(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(out!=null){ out.close(); } } } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req, resp); } }
/** * 處理是否開啟GPS信息收集的servlet * @author yqq_coder * */ public class StartAction extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); resp.setCharacterEncoding("utf-8"); PrintWriter out=resp.getWriter(); String nameAction=(String)req.getAttribute("nameAction"); String mAction=req.getParameter("mAction"); //查詢服務器端數據庫並獲得返回值 if(mAction!=null&&mAction.equals("find_gps_switcher1")){ System.out.println("定時器服務查詢:"+mAction); try { String result=DbUtis.getGPSStaus(); if(result!=null&&result.equals("start_gps")){ out.write("GPS_start"); out.flush(); } if(result!=null&&result.equals("end_gps")){ out.write("GPS_stop"); out.flush(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(out!=null){ out.close(); } } } } }
import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class DbUtis { private static String ip="192.168.1.134"; private static Connection conn; public static JSONArray getData(String name) throws SQLException { Listinfos = new ArrayList (); JSONArray array = new JSONArray(); GpsInfo info = null; JSONObject jsonObject = null; PreparedStatement pstmt =null; ResultSet rs = null; // 連接數據庫 try { Class.forName("com.mysql.jdbc.Driver"); // 鏈接數據庫 conn = DriverManager.getConnection( "jdbc:mysql://"+ip+":3306/test", "root", "admin"); // Statement stmt =(Statement) conn.prepareStatement(""); String sql="select name,longitude,latitude from gpsinfos where name=?"; pstmt= conn.prepareStatement(sql); pstmt.setString(1, name); rs = pstmt.executeQuery(); // 從結果集裡取值 //System.out.println(rs.getRow()); while (rs.next()) { // info=new GpsInfo(); // info.setLatitude(rs.getString(0));//緯度 // info.setLongitude(rs.getString(1)); // infos.add(info); // info=null; jsonObject = new JSONObject(); try { jsonObject.put("name", rs.getString("name")); jsonObject.put("longitude", rs.getString("longitude")); jsonObject.put("latitude", rs.getString("latitude")); array.put(jsonObject); jsonObject=null; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if (rs != null) { rs.close(); rs = null; } if(pstmt!=null) { pstmt.close(); pstmt = null; } if (conn != null) { conn.close(); conn = null; } } return array; } public static String getGPSStaus() throws SQLException { String result=null; PreparedStatement pstmt =null; ResultSet rs = null; // 連接數據庫 try { Class.forName("com.mysql.jdbc.Driver"); // 鏈接數據庫 conn = DriverManager.getConnection( "jdbc:mysql://"+ip+":3306/test", "root", "admin"); // Statement stmt =(Statement) conn.prepareStatement(""); String sql="select gps_staus from gps_switcher "; pstmt= conn.prepareStatement(sql); rs = pstmt.executeQuery(); // 從結果集裡取值 //System.out.println(rs.getRow()); while (rs.next()) { result=rs.getString("gps_staus"); } return result; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if (rs != null) { rs.close(); rs = null; } if(pstmt!=null) { pstmt.close(); pstmt = null; } if (conn != null) { conn.close(); conn = null; } } return null; } public static void insertGpsInfos(GpsInfo info) throws SQLException{ PreparedStatement pstmt = null; // 數據庫表達式 ResultSet rs = null; // 結果集 try { /*加載驅動*/ //192.168.173.1 Class.forName("com.mysql.jdbc.Driver"); /*連接到數據庫*/ conn = DriverManager.getConnection( "jdbc:mysql://"+ip+":3306/test", "root", "admin"); String sql = "insert into gpsinfos (name,longitude,latitude) values (?,?,?)"; /* 獲取表達式*/ pstmt = conn.prepareStatement(sql); pstmt.setString(1,info.getName()); pstmt.setString(2, info.getLongitude()); pstmt.setString(3, info.getLatitude()); /* 插入數據*/ pstmt.execute(); /* 執行SQL*/ rs = pstmt.executeQuery("select * from gpsinfos"); /* 查看裡面的數據*/ while (rs.next()) { System.out.println("插入的數據姓名=" + rs.getString("name")); System.out.println("插入的數據經度=" + rs.getString("longitude")); System.out.println("插入的數據緯度=" + rs.getString("latitude")); } } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(rs!=null){ rs.close(); } if(pstmt!=null) { pstmt.close(); pstmt = null; } if(conn!=null){ conn.close(); } } } public static void insertGpsSatus(String staus) throws SQLException{ PreparedStatement pstmt = null; // 數據庫表達式 ResultSet rs = null; // 結果集 try { /*加載驅動*/ //192.168.173.1 Class.forName("com.mysql.jdbc.Driver"); /*連接到數據庫*/ conn = DriverManager.getConnection( "jdbc:mysql://"+ip+":3306/test", "root", "admin"); String sql = "insert into gps_switcher (gps_staus) values (?)"; /* 獲取表達式*/ pstmt = conn.prepareStatement(sql); pstmt.setString(1,staus); /* 插入數據*/ pstmt.execute(); /* 執行SQL*/ rs = pstmt.executeQuery("select * from gps_switcher"); /* 查看裡面的數據*/ while (rs.next()) { System.out.println("插入的數據GPS狀態=" + rs.getString("gps_staus")); } } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(rs!=null){ rs.close(); } if(pstmt!=null) { pstmt.close(); pstmt = null; } if(conn!=null){ conn.close(); } } } public static void deleteGpsSatus() throws SQLException{ PreparedStatement pstmt = null; // 數據庫表達式 ResultSet rs = null; // 結果集 try { /*加載驅動*/ //192.168.173.1 Class.forName("com.mysql.jdbc.Driver"); /*連接到數據庫*/ conn = DriverManager.getConnection( "jdbc:mysql://"+ip+":3306/test", "root", "admin"); String sql="delete from gps_switcher"; pstmt = conn.prepareStatement(sql); pstmt.execute(); } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(rs!=null){ rs.close(); } if(pstmt!=null) { pstmt.close(); pstmt = null; } if(conn!=null){ conn.close(); } } } public static void createTable() throws SQLException{ try { //Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://"+ip+":3306/test","root","admin"); String sql = "CREATE TABLE gpsinfos (id int primary key auto_increment, name varchar(64) not null, longitude varchar(256) not null , latitude varchar(256) not null );"; //CREATE TABLE gpsinfos (id int primary key auto_increment, gps_staus varchar(16) not null) //gps_switcher(id int primary key auto_increment, gps_staus varchar(16) not null unique) PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[]args) throws SQLException{ /* try { createTable(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ //insertGpsInfos(new GpsInfo("小強","5225.1111111","5333333.888222")); System.out.println(DbUtis.getData("Lihua")); } }
控制端主要是發送幾個GET方式的請求,這裡就不再貼代碼了。
幾個請求:
"http://"+ConentValues.serverIp+":8080/MyServer/MyTest?mAction=find_gps_switcher";
"http://"+ConentValues.serverIp+":8080/MyServer/StartAction?mAction=find_gps_switcher1";
http://172.22.122.1:8080/MyServer/MyTest?longitude=111&latitude=222&height=1000&name=Test
http://172.22.122.1:8080/MyServer/MyTest?namereq=Test
demo下載地址:http://download.csdn.net/detail/u014600432/8209931
前面我們講解了系統截屏按鍵處理流程,HOME按鍵處理流程,今天再來講解一下電源開關機按鍵事件流程,當然這也是系統按鍵處理流程方面的最後一篇博客了。和截屏按鍵、HOME按鍵
1. Overview這是一篇翻譯文章,自己作為android工程師以來,第一次翻譯國外網站的文章,所以不免會有一些遺漏和錯誤。原文請參考RecyclerView 是一種
0. 前言Android的屏幕適配,即使得某一元素在Android不同尺寸、不同分辨率的手機上具備相同的顯示效果,這個問題一直以來都是我們Android開發者不得不面對的
前言Handler是Android消息機制的上層接口,平時使用起來很方便,我們可以通過它把一個任務切換到Handler所在的線程中去運行。而最常用的就是拿來從子線程切換到