Socket服务

首先开启一个启动Socket的服务

publicclassSocketNetService extends Service{

privatefinal String TAG = "SocketNetService";

publicstatic Thread NetThread;

publicstatic Socket socket;

private InetAddress address;

publicstaticbooleanisFristConn = true;

publicstatic BufferedWriter bw = null;

publicstatic BufferedReader br = null;

publicstatic SocketIOWriterNet writerThread = null;

publicstatic UpUserAddress upUserAddress= null;

private String ip;

private Handler handler = new Handler() {

@Override

publicvoid handleMessage(Messagemsg) {

super.handleMessage(msg);

switch (msg.what) {

case 200:

break;

case 404:

NetListenerUtil.clostAllNet(SocketNetService.this);

break;

}

}

};

@Override

public IBinder onBind(Intentintent) {

returnnull;

}

@Override

publicvoid onCreate() {

super.onCreate();

}

@Override

publicint onStartCommand(Intentintent, intflags, intstartId) {

Util.logh("SOCKET","Content.IS_CANCEL_LOGIN_NET: "+Content.IS_CANCEL_LOGIN_NET+"getSharedPreferencesoffinnet:"+getSharedPreferences("OFF_IN_Net",MODE_PRIVATE).getString("offinnet","")+"Content.IS_IN_SOCKET:"+Content.IS_IN_SOCKET);

if(!Content.IS_CANCEL_LOGIN_NET&&(getSharedPreferences("OFF_IN_Net",MODE_PRIVATE).getString("offinnet","")).equals("0")&&!Content.IS_IN_SOCKET){

Content.IS_IN_SOCKET=true;

Util.logh("SOCKET","NetThread: "+NetThread+ "socket:"+socket);

if (NetThread == null || socket == null) {

NetThread = new Thread(new Runnable() {

@Override

publicvoid run() {

connSocket();

}

});

NetThread.start();

}

}

returnsuper.onStartCommand(intent,flags, startId);

}

privatevoid connSocket() {

if (socket == null) {

try {

try

{

ip=java.net.InetAddress.getByName(Content.SOCKET).getHostAddress();

Util.logh("SOCKET","ip:"+ip);

}

catch(UnknownHostException e)

{

}

address = InetAddress.getByName(ip);

socket = new Socket(address, 9200);

socket.setSoTimeout(5000);

bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

if(SocketNetService.writerThread==null){

writerThread = newSocketIOWriterNet(SocketNetService.this);

try{

SocketNetService.writerThread.start();

}catch(Exception e){

e.printStackTrace();

}

}

Stringstr = CreateSocketJson.LoginInfoJson(SocketNetService.this);

if(SocketNetService.writerThread!=null&&str!=null){

//

SocketNetService.writerThread.SetStr(str);

Util.logh("SOCKET","SocketNetService.writerThread.SetStr(str): "+str);

//

SocketNetService.writerThread.getStr();

}

}catch(UnknownHostException e) {

e.printStackTrace();

Messagemsgs2 = Message.obtain();

msgs2.what = 404;

Util.logh("SOCKET","404)UnknownHostException: ");

handler.sendMessage(msgs2);

}catch(IOException e) {

e.printStackTrace();

Message msgs3 = Message.obtain();

msgs3.what = 404;

Util.logh("SOCKET","404)IOException: ");

handler.sendMessage(msgs3);

}

}

}

@Override

publicvoid onDestroy() {

super.onDestroy();

if(socket!=null){

socket = null;

}

if(NetThread!=null){

NetThread = null;

}

NetListenerUtil.clostAllNet(SocketNetService.this);

Util.logh("SOCKET","SocketNetService.onDestroy: ");

}

}

然后通过这个全局的写和读的线程,如下:对于数据进入读写处理:

publicclassSocketIOWriterNet extends Thread {

private JSONObject jsonObject;

private Context context;

privatebooleanisMainInit = true;

public SocketIOWriterNet(Context context) {

this.context = context;

}

/**

* 发送

*

* @param str

*/

publicvoid SetStr(String str) {

try {

if (SocketNetService.bw != null) {

SocketNetService.bw.write(str);

SocketNetService.bw.flush();

}else{

NetListenerUtil.clostAllNet(context);

}

}catch(Exception e) {

/*

* System.out.println("网络错误...哈哈哈哈哈");

* NetListenerUtil.clostAllNet(context);

*/

e.printStackTrace();

}

}

publicvoid getStr() {

try {

while (isMainInit == true) {

System.out.println("whiele vdsfgvsdf");

try {

SocketNetService.socket.sendUrgentData(0xFF);

Util.logh("SOCKET","getStr() : SocketNetService.socket.sendUrgentData(0xFF);");

}catch(Exception e) {

Util.logh("SOCKET","getStr() :SocketNetService.socket.sendUrgentData(0xFF); Exception e");

NetListenerUtil.clostAllNet(context);

break;

}

if(SocketNetService.br!=null){

Stringline = SocketNetService.br.readLine();

Util.logh("SOCKET","SocketNetService.br.readLine();");

if (line != null) {

System.out.println("line-->"+ line);

jsonObject = new JSONObject(line);

IntentbroadIntent = newIntent();

broadIntent.setAction(BroadCastFinals.BROAD_OPER_CONN);

Bundlebundle = newBundle();

bundle.putString("action",jsonObject.getString("action"));

bundle.putString("json", line);

broadIntent.putExtra("bundle",bundle);

context.sendBroadcast(broadIntent);

}

}

Util.logh("SOCKET","if(SocketNetService.br!=null)");

if(SocketNetService.br!=null)

SocketNetService.br.ready();

Thread.sleep(200);

}

}catch(IOException e) {

Util.logh("SOCKET","getStr() : catch (IOException e){again;1111111111111111111111111111");

getStr();

}catch(InterruptedException e) {

getStr();

Util.logh("SOCKET","getStr() : catch(InterruptedException e) {again;1111111111111111111111111111");

}catch(JSONException e) {

getStr();

Util.logh("SOCKET","getStr() : catch (JSONException e){again;1111111111111111111111111111");

}

}

publicvoid setInitBooleanMain(boolean bool) {

isMainInit = bool;

}

}

Socket连接异常时,处理时,将后台上传地理位置信息的和那些什么Socket有关的全部关闭:

publicstaticvoid clostAllNet(Contextcontext) {

// 关闭上传位置

if (OperConnReceiver.upUserAddress!= null&& UpUserAddress.client !=null){

UpUserAddress.stopLocationClient();

//OperConnReceiver.upUserAddress = null;

}

// 关闭IO

if (SocketNetService.br != null) {

/* try{

SocketNetService.br.close();

}catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

*/ SocketNetService.br = null;

}

if (SocketNetService.bw != null) {

/* try{

SocketNetService.bw.close();

}catch (IOException e) {

e.printStackTrace();

}

*/ SocketNetService.bw = null;

}

// 关闭Socket连接

if (SocketNetService.socket != null) {

/* try{

SocketNetService.socket.close();

}catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

*/ SocketNetService.socket = null;

}

// 关闭启动Socket的线程

if (SocketNetService.NetThread != null) {

SocketNetService.NetThread = null;

}

// 退出循环读取服务器数据的While

if (SocketNetService.writerThread != null) {

SocketNetService.writerThread.setInitBooleanMain(false);

}

// 关闭向服务器读写数据的线程

if (SocketNetService.writerThread != null) {

SocketNetService.writerThread = null;

}

// 关闭服务

if(MainActivity.serviceIntent!=null){

context.stopService(MainActivity.serviceIntent);}

Util.logh("SOCKET","NetListenerUtil: "+Content.IS_IN_SOCKET);

if(Content.IS_IN_SOCKET){

boolean isLogin = context.getSharedPreferences("isBoolean", context.MODE_PRIVATE).getBoolean("is_login",false);

boolean isconnect =Content.IS_CONNECT_NET;

if(isconnect&&isLogin){

Intentintent = newIntent();

intent.setAction(BroadCastFinals.BROAD_LISTENER_SOCKET);

Bundlebundle = newBundle();

bundle.putInt("flag", 0);

intent.putExtra("bundle",bundle);

context.sendBroadcast(intent);

}

}

}

然后通过广播进行重连的处理:

publicclassListenerSocketReceiverextendsBroadcastReceiver {

@Override

publicvoid onReceive(final Context context, Intentintent) {

// ***网络的状态

Bundlebundle = intent.getBundleExtra("bundle");

Util.logh("SOCKET","bundle.getInt(flag) == 0 : "+bundle.getInt("flag")+"bundle"+bundle);

if (bundle.getInt("flag") == 0 &&bundle != null){ // Socket连接断开

// 第一次启动为true

SocketNetService.isFristConn = true;

// 循环使其连接

new Thread(new Runnable() {

@Override

publicvoid run() {

try {

Util.logh("SOCKET","Thread.sleep(5000) : ");

Thread.sleep(5000);// 休眠5

boolean isLogin = context.getSharedPreferences("isBoolean", context.MODE_PRIVATE).getBoolean("is_login",false);

Util.logh("SOCKET", "Thread.sleep(5000)Content.IS_CONNECT_NET: "+Content.IS_CONNECT_NET+"isLogin: "+isLogin+"OFFINNET :"+context.getSharedPreferences("OFF_IN_Net",context.MODE_PRIVATE).getString("offinnet", ""));

if(Content.IS_CONNECT_NET&&isLogin&&(context.getSharedPreferences("OFF_IN_Net",context.MODE_PRIVATE).getString("offinnet", "")).equals("0")){

Content.IS_IN_SOCKET =false;

context.startService(MainActivity.serviceIntent);

}else{

Util.logh("SOCKET","return:");

return;

}

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}).start();

}

连接成功后的读写操作:

就是将从后台读到的数据,通过广播的形式又发送到广播接收者即可:

publicclassOperConnReceiver extends BroadcastReceiver {

private Context context;

private String action_result;

private String json_result;

private JSONObject jsonObject;

publicstatic UpUserAddress upUserAddress;

privatebooleanisOpenAddress = false;

private Intent intent;

@Override

publicvoid onReceive(Contextcontext, Intent intent) {

this.context = context;

Bundlebundle = intent.getBundleExtra("bundle");

action_result =bundle.getString("action");

json_result = bundle.getString("json");

List<HelpMsgModel>helpMsgList;

switch (action_result) {

case SocketActionFinals.ACTION_RESPONSE_INIT: // 初始化连接

initConn();

break;

case SocketActionFinals.ACTION_TASK_INFO: // 获取任务列表的信息

System.out.println("ACTION_TASK_INFO");

helpMsgList = ParserJson.taskListInfo(json_result);

if(helpMsgList!=null&& helpMsgList.get(0).getTaskId()!=null){

MainActivity.showListTask(helpMsgList, context);

}

break;

case SocketActionFinals.ACTION_IS_CATCHED:

try {

jsonObject = new JSONObject(json_result);

String taskId = jsonObject.getString("assignment_id");

MainActivity.isCatchedTask(taskId);

}catch(JSONException e) {

e.printStackTrace();

}

break;

case SocketActionFinals.ACTION_CATCH_ASSIGNMENT:

ConfirmOrdersActivity.nextPage(json_result,context);

break;

case SocketActionFinals.ACTION_RESPONSEEXECUTE:

RescueActivity.nextPage(json_result,context);

break;

case SocketActionFinals.ACTION_SCREEN_OFF:

ToServerAddress();

break;

case SocketActionFinals.ACTION_FINISH_ASSIGNMENT:

ExecuteOrderActivity.nextPage(json_result, context);

break;

//终止任务请求

case SocketActionFinals.ACTION_STOP_ASSIGNMENT:

if(!Content.IS_STOP_IN_EXECUTEORDERACTIVIITY){

RescueActivity.nextPage1(json_result, context);

}else{

ExecuteOrderActivity.nextPage1(json_result, context);

}

break;

}

}

// Socket初始化连接的方法

privatevoid initConn(){

try {

jsonObject = new JSONObject(json_result);

Stringcode_result = jsonObject.getString("err_code");

System.out.println("code_result-->"+ code_result);

if(code_result.equals("0")){ // 初始话成功,可采取后续操作

if(!isOpenAddress){

System.out.println("isOpenAddress-->"+ isOpenAddress);

isOpenAddress = true;

ToServerAddress();

}

}else{ // 初始化失败。重新开始初始化

/*

if(isOpenAddress){

isOpenAddress= false;

}

System.out.println("重新初始化");

Thread.sleep(3000);

alreadyConnInit();*/

NetListenerUtil.clostAllNet(context);

Util.logh("SOCKET","初始化失败后,直接调用这个关闭服务,然后重新开始落");

}

}catch(Exception e) {

NetListenerUtil.clostAllNet(context);

Util.logh("SOCKET","初始化失败后,直接调用这个关闭服务,然后重新开始落是在Exception里开始这个重新初始化");

}

}

// 初始化Socket成功后,启动上传用户地理坐标的信息

privatevoid ToServerAddress(){

new Thread(new Runnable() {

@Override

publicvoid run() {

upUserAddress= newUpUserAddress(context.getApplicationContext());

upUserAddress.addressInfo();

Util.logh("SOCKET","upUserAddress.addressInfo()");

}

}).start();

}

privatevoid alreadyConnInit(){

new Thread(new Runnable() {

@Override

publicvoid run() {

Stringstr = CreateSocketJson.LoginInfoJson(context.getApplicationContext());

System.out.println("str!!-->"+str);

//

SocketNetService.writerThread.SetStr(str);

//

SocketNetService.writerThread.getStr();

}

}).start();

}

}

广播接收者处理各种后台发过来的数据,然后进行处理:

其实地理位置的初始化是通过在得到这个初始化信息时进行处理的:

publicclassUpUserAddress {

// 调用百度地图的实时定位,上传坐标位置

publicstatic LocationClient client;

private Context context;

privatedoublelatitude = 0.0;

privatedoublelongitude = 0.0;

privateinttimeOut = 40;

private LatLng latLng1 = null;

private LatLng latLng2 = null;

private SharedPreferences userInfo;

private JSONObject jsonObject = null;

public UpUserAddress(Context context){

this.context = context;

userInfo =context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);

jsonObject = new JSONObject();

}

publicvoid addressInfo(){

Looper.prepare();

System.out.println("addressInfo()");

client = new LocationClient(context);

client.registerLocationListener(new MyLoactionListener());

LocationClientOptionoption = newLocationClientOption();

option.setOpenGps(true);

option.setCoorType("bd09ll");

option.setScanSpan(5000);

client.setLocOption(option);

client.start();

Looper.loop();

}

privateclass MyLoactionListener implementsBDLocationListener{

// 返回定位的坐标

@Override

publicvoidonReceiveLocation(BDLocation arg0) {

if(arg0 == null){

return;

}

// 获取初始位置

Stringlatitude1 =userInfo.getString("loginLatitude","");

Stringlongitude1 = userInfo.getString("loginLongitude","");

LatLnglatLng11 = newLatLng(Double.valueOf(latitude1) , Double.valueOf(longitude1) );

Util.logh("ADDRESS",latitude1+"1111111111111"+longitude1);

LatLnglatLng22;

if(arg0.getLatitude()==0||arg0.getLongitude()==0){

latLng22= latLng11;

}else{

latLng22 = new LatLng(arg0.getLatitude() ,arg0.getLongitude());

}

if(DistanceUtil.getDistance(latLng11,latLng22)>=3.0||timeOut==0){

Stringjson =CreateSocketJson.sendMyLontitude(context, arg0.getLatitude()+"", arg0.getLongitude()+"");

if(SocketNetService.writerThread!=null){

SocketNetService.writerThread.SetStr(json);

}

latitude = arg0.getLatitude();

longitude = arg0.getLongitude();

latLng1 = new LatLng(latitude , longitude);

timeOut = 28;

Util.logh("ADDRESS",latitude+"dddddd"+longitude);

userInfo.edit().putString("loginLongitude",arg0.getLongitude()+"").putString("loginLatitude", arg0.getLatitude()+"").commit();

}

timeOut--;

}

@Override

publicvoid onReceivePoi(BDLocationarg0) {

}

}

/**

* 上传用户的坐标点

* @param lat 坐标的纬度

* @param longt 坐标的经度

*/

privatevoid upUserAddress(Stringlat , String longt){

try {

String uploadTaskId =context.getSharedPreferences("UploadTASKID",Context.MODE_PRIVATE).getString("taskId","");

jsonObject.put("uid" , userInfo.getString("uId", ""));

jsonObject.put("company_id", userInfo.getString("companyId",""));

jsonObject.put("action","UpPosition");

jsonObject.put("latitude",lat);

jsonObject.put("longitude",longt);

jsonObject.put("assignment_id",uploadTaskId);

Stringjson = "app"+ jsonObject.toString()+ "\r\n\r\n";

if(SocketNetService.writerThread!=null){

SocketNetService.writerThread.SetStr(json);

}

}catch(JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

publicstaticvoid stopLocationClient(){

if(client!=null){

client.stop();

client = null;

}

}

publicboolean isStartClient(){

returnclient.isStarted();

}


更多相关文章

  1. Android下拉刷新上拉加载控件的使用
  2. Android获取、设置Wifi状态
  3. Android中setContentView(int laoutId) 干了些什么事
  4. Android的网络与通信
  5. Android开发中出现Attempt to invoke virtual method...on a nul
  6. Android禁止截屏
  7. Android调用JNI出错 java.lang.UnsatisfiedLinkError: No implem
  8. Android(安卓)全局异常错误或崩溃捕捉
  9. Android网络连接处理学习笔记

随机推荐

  1. Android(安卓)花里胡哨的加载Loading动画
  2. Android(安卓)之 自动提示功能(AutoCompl
  3. Android移动应用开发_点击切换图片形成图
  4. Android(安卓)笔记 - 圆形头像
  5. Android一些系统路径的使用
  6. Android(安卓)闹钟设置最新版
  7. sqlite3 常用命令 for android
  8. Intent 和 Intent Filter
  9. Both setBehindContentView must be call
  10. 不能创建处理器 Can't create handler in