两部android设备通过服务器转发实现通信简单demo

来源:互联网 发布:oracle默认数据库 编辑:程序博客网 时间:2024/05/22 06:59

实现该通信的基本思路是:利用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}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.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() {@Overridepublic 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 blocke.printStackTrace();}}},d2, 5000);}}

Gps信息收集的关键代码:

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() {}@Overridepublic IBinder onBind(Intent intent) {if(D){Log.i("GPS服务数据收集","IBinder()");}return null;}@Overridepublic 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();}@Overridepublic 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() {@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {// TODO Auto-generated method stub}@Overridepublic void onProviderEnabled(String provider) {// TODO Auto-generated method stub}@Overridepublic void onProviderDisabled(String provider) {// TODO Auto-generated method stub}@Overridepublic void onLocationChanged(Location location) {if(location==null){return;}//updateLocation(location);mLocation=location;new AsyncTask<Void, Void, Void>() {private String str=null;@Overrideprotected 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 blocke.printStackTrace();}/*GpsInfo info=new GpsInfo();info.setLongitude(longitude+"");info.setLatitude(latitude+"");info.setHeight(height+"");mGpSinfoDao.addGpsInfo(info);info=null;*/return null;}@Overrideprotected void onPostExecute(Void result) {Toast.makeText(getApplicationContext(), str,0).show();};}.execute();            }        });return super.onStartCommand(intent, flags, startId);}@Overridepublic 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() {@Overridepublic 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 blocke.printStackTrace();}}},d2, 5000);}}

2、服务端利用servlet来处理各自的请求和响应

关键代码:

(1)处理GPS信息上传到服务器的servlet

public class MyTest extends HttpServlet {//private List<GpsInfo> infos;private GpsInfo info;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected 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 blocke.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 blocke.printStackTrace();}finally{/*if(out!=null){out.close();}*/}}}

(2)
/** * 处理gps开关信息的servlet * @author yqq_coder * */public class GpsOnOffAction extends HttpServlet {@Overrideprotected 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 blocke.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 blocke.printStackTrace();}//req.setAttribute("nameAction", "GPS_stop"); //req.getRequestDispatcher("/MyTest").forward(req, resp);  }out.flush();}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubsuper.service(req, resp);}}
/** * 查询GPS信息 * @author yqq_coder * */public class QurAction extends HttpServlet {private JSONArray infos;@Overrideprotected 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=Testif(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 blocke.printStackTrace();}finally{if(out!=null){out.close();}}}}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubdoPost(req, resp);}}

/** * 处理是否开启GPS信息收集的servlet * @author yqq_coder * */public class StartAction extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected 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 blocke.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 {List<GpsInfo> infos = new ArrayList<GpsInfo>();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 blocke.printStackTrace();} }} catch (Exception e) {// TODO Auto-generated catch blocke.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 blocke.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 blocke.printStackTrace();}}public static void main(String[]args) throws SQLException{/*try {createTable();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {} catch (SQLException e) {// TODO Auto-generated catch blocke.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


0 0
原创粉丝点击