gpt4 book ai didi

java - 如果连接失败如何保持连接并重新连接

转载 作者:行者123 更新时间:2023-12-01 13:34:54 24 4
gpt4 key购买 nike

我有一个始终运行的服务(即使我的主应用程序未处于 Activity 状态)。

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

我的问题:

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

两种场景:

1) A. 由于服务器故障导致连接失败 B. 服务尝试重新建立连接。 C. 服务器上线。 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);
}
}

最佳答案

请引用我的回答here ,其中显示了如何在连接或未连接时监控 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);

希望有帮助。

关于java - 如果连接失败如何保持连接并重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21361291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com