Java 如何保持连接并在连接失败时重新连接 我有一个一直运行的服务(即使我的主应用程序不活动)。

Java 如何保持连接并在连接失败时重新连接 我有一个一直运行的服务(即使我的主应用程序不活动)。,java,android,sockets,Java,Android,Sockets,应用程序建立连接并将流传递给服务。 然后,服务一直(每秒)读取这些流,并通知我是否接收到流中的数据 我的问题: 如何保持连接,我的意思是如果我失去了连接,如何重新建立连接。 (即丢失wifi和移动数据并稍后获取),我希望该服务一直尝试连接,直到找到可用的互联网连接(例如wifi) 两种情况: 1) A.由于服务器故障导致连接失败B.尝试重新建立连接的服务。服务器上线了。D.服务成功连接 2) A.由于Wifi/移动数据不可用,连接失败。B.尝试重新建立连接的服务。C.现在有数据(wifi/移动)

应用程序建立连接并将流传递给服务。 然后,服务一直(每秒)读取这些流,并通知我是否接收到流中的数据

我的问题:

如何保持连接,我的意思是如果我失去了连接,如何重新建立连接。 (即丢失wifi和移动数据并稍后获取),我希望该服务一直尝试连接,直到找到可用的互联网连接(例如wifi)

两种情况:

1) A.由于服务器故障导致连接失败B.尝试重新建立连接的服务。服务器上线了。D.服务成功连接

2) A.由于Wifi/移动数据不可用,连接失败。B.尝试重新建立连接的服务。C.现在有数据(wifi/移动)可用。D.服务成功连接

怎么做? 要点:就像Whatsapp服务一样,即使在失去互联网连接后,也要保持连接并重新获得它

我的服务代码:

public class seekNet extends Service {


    private Message newMessageArrived = new Message();

    Intent intent1;
    private final IBinder Ibinder = new MyBinder();


    @Override
    public IBinder onBind(Intent intent) {
    this.intent1=intent;

        return Ibinder;
    }
    boolean streamsOK=true;
    boolean SoktOK=true;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
         streamsOK=true;
         SoktOK=true;
        Timer t_s = new Timer();
        t_s.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Message connected =new Message();
                connected.setBody("Is the connection on?");
                connected.type=402;

                try {
                    SendRandom.ObjectOutServerchtStstus.writeUnshared(connected);
                 }catch (StreamCorruptedException stream){
                    streamsOK=false;

            }catch (SocketException e) {
                    SoktOK=false;
                    e.printStackTrace();
                }catch (IOException io){
                    io.printStackTrace();
                }
                try {
                    if((SendRandom.ObjectInServerchtStstus.readUnshared())==null)
                        Log.d("SOMAA","Connection Down1");
                }catch (SocketException e){

                    Log.d("SOMAA","Connection Down2");
                }catch (StreamCorruptedException stream){
                    Log.d("SOMAA","Connection to service Down");

                }


                catch (IOException e) {

                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        },10,100);

//-------| you can ignore the above part, it's may attempt and not complete |--

        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    newMessageArrived = (Message) SendRandom.ObjectInServercht.readUnshared();
                }catch (StreamCorruptedException stream){
                    Log.d("SOMAA","Connection to service Down2");
                    return;
                }catch (SocketException so)
                {  Log.d("SOMAA","Connection to service Down2 Socket error");
                    return;}
                catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }catch(NullPointerException nu){
                nu.printStackTrace();
            }
                 if ( newMessageArrived!= null) {

                        Intent messagesI = new Intent("Messages");
                        messagesI.putExtra("body", newMessageArrived.getBody());
                        messagesI.putExtra("From", newMessageArrived.getFrom());
                        messagesI.putExtra("To", newMessageArrived.getTo());
                        messagesI.putExtra("toGender", newMessageArrived.getTogender());
                        messagesI.putExtra("SenderGender", newMessageArrived.my_gender);
                        messagesI.putExtra("msgType", newMessageArrived.type);
                        messagesI.putExtra("url", newMessageArrived.url);
                        messagesI.putExtra("SenderID", newMessageArrived.userID);
                        messagesI.putExtra("Time", newMessageArrived.getTime());
                        messagesI.putExtra("msgId", newMessageArrived.msgID);
                        messagesI.setAction("com.esmaeel.incomIM");
                        if(newMessageArrived.type==MessageType.TextMessage)
                        {
                         pushNotification(newMessageArrived);
                        }
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcastSync(messagesI);
                     newMessageArrived=null;
                    }

                try{ // check the connection
            SendRandom.ObjectOutServercht.writeUnshared(new Message());
                }catch (StreamCorruptedException st){
                    Log.d("SOMAA","Stream currpted");
                   streamsOK=false;
                    if(SendRandom.sktChat.isClosed())
                    { SoktOK=false;
                    Log.d("SOMAA","Socket closed!!");
                    }

                }catch (SocketException so){
                    Log.d("SOMAA","socket error "+ so.getMessage());
                    SendRandom.isConnectedSucess=false;
                    SoktOK=false;
                }catch (IOException ex){
                    Log.d("SOMAA","IO error");
                }
if(SoktOK&&!streamsOK){

    try {
        Log.d("SOMAA","1. Trying to Fix the streams");

        SendRandom.ObjectOutServercht = new ObjectOutputStream( SendRandom.sktChat.getOutputStream());
        SendRandom.ObjectInServercht = new ObjectInputStream( SendRandom.sktChat.getInputStream());

    } catch (Exception e) {
        Log.d("SOMAA","2. connot Fix the streams");

        e.printStackTrace();
    }


}
 if(!SoktOK){
     Log.d("SOMAA","no socket!, Will call conectNet0().execute();");//conectNet0()=Async class that establish connection.

     new conectNet0().execute();
     Log.d("SOMAA"," conectNet0().execute(); called!");

 }

            }
        }, 10, 100);
        return Service.START_STICKY;
    }

    public class MyBinder extends Binder {

        seekNet getService() {
        return seekNet.this;
        }
    }

    @Override

    public void onCreate() {
        Log.d("SOMAA", "OnCreate");
        newMessageArrived.url = "temp";
        newMessageArrived.setTogender("Temp");
        newMessageArrived.my_gender = "Temp";
        newMessageArrived.type = 9;
        newMessageArrived.userID = "temp";
        super.onCreate();
    }

    @Override

    public void onDestroy() {
        Log.d("SOMAA", "onDestroy Service");
    }

    public void pushNotification(Message arrivedMSG) {
        String msgbdy = arrivedMSG.getBody();



        PendingIntent pIntent = PendingIntent.getActivity(this, 0,intent1, 0);

        // build notification
        Notification n = new Notification.Builder(this)
                .setContentTitle("new message")
                .setContentText("Strange: "+ msgbdy)
                .setSmallIcon(R.drawable.notify)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .addAction(R.drawable.notify, msgbdy, pIntent)
                .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // hide the notification after its selected
        n.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, n);
    }
}

请参考我的答案,其中显示了在WIFI连接或未连接时如何监控WIFI,并且您可以在那里启动服务:

public class NetworkChangeReceiver extends BroadcastReceiver {

      @Override
public void onReceive(final Context context, final Intent intent) {

    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 

    boolean isConnected = wifi != null &&   
                wifi.isConnected() ;

    if (isConnected ) {
        // Do something

        Log.d("Netowk Available ", "Flag No 1");
    }else {
       Log.d("Netowk not available  Available ", "Flag No 2");

     }
  }
}
并使用AlarmManager每X秒启动一次服务,如下所示:

Calendar cal = Calendar.getInstance();

Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent); 
希望有帮助

我找到了解决方案: 检测“半开连接”
当我检测到我为我的应用程序设置了一个标志,以尝试重新连接,直到成功。然后将该标志设置为连接模式。(标志是简单的布尔变量)

请提供您服务的源代码谢谢,答案是关于检测Wifi状态,但我想知道每个特定时间连接是否打开!,之后(根据你的回答),我寻找原因,然后重新连接。未回答的部分:1。“要知道每次连接是否打开!”2。要了解断开连接的原因。。。3.尝试重新连接!通过BroadcastReceiver,每次wifi状态更改时,您都会收到通知,这样您就知道何时连接或断开连接了。我没有告诉您,我是服务器的所有者,那么,如果服务器出现故障???而无线上网呢?:),你的回答对我帮助很大,但这不是我真正需要的!告诉我您还需要什么,以便我可以改进我的回答以检测断开连接!,并恢复连接,而不管断开连接的原因如何。。