实现该通信的基本思路是:利用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);
}
}
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() {
}
@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<Void, Void, Void>() {
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);
}
}
2、服务端利用servlet来处理各自的请求和响应
关键代码:
(1)处理GPS信息上传到服务器的servlet
public class MyTest extends HttpServlet {
//private List<GpsInfo> infos;
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();
}*/
}
}
}
(2)
/**
* 处理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 {
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 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