これを説明する方法は完全にはわかりませんが、AsyncTaskは初めてで、UDPパケットをサーバーに送信しようとしています。応答があれば、オフラインではなくオンラインに設定されます。現在、アプリを最初に開いたときは正しく機能しますが、新しいページが読み込まれると、サーバーはまだオンラインであるにもかかわらずオフラインであると表示されます。何が悪いのかわかりません。AsyncTaskを誤って実行しているのですか、それともその程度ですか?それが私がここで考えることができる唯一のことです。
CheckStatus.java
import java.io.IOException;
import java.net.*;
public class CheckStatus {
//Check if the server is online
public static boolean check() {
try {
byte[] receiveData = new byte[1024];
InetAddress address = InetAddress.getByName("11.11.11.11");
//create socket
DatagramSocket clientSocket = new DatagramSocket();
//set timeout
clientSocket.setSoTimeout(1000);
//send packet
DatagramPacket p = new DatagramPacket(Integer.toBinaryString(0x0006000000).getBytes(), 5, address, 44462);
.send(p);
//try to receive packet from server
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.close();
return true;
} catch (Exception e) {
//if nothing is received set the the server status offline
return false;
}
}
}
CheckStatusTask.java
import android.os.AsyncTask;
class CheckStatusTask extends AsyncTask<Object, Object, Boolean> {
private static boolean online;
protected Boolean doInBackground(Object... arg0) {
boolean flag = CheckStatus.check();
return flag;
}
protected void onPostExecute(Boolean flag) {
online = flag;
}
public static boolean getOnline(){
return online;
}
}
main.java
import android.os.Bundle;
import android.view.View;
import com.swgproject.projectswg.ActionBar;
public class Main extends ActionBar {
//Include res/layout/main.xml
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View background = findViewById(R.id.status);
View status = findViewById(R.id.image);
new CheckStatusTask().execute();
if(CheckStatusTask.getOnline()){
background.setBackgroundResource(R.layout.offline);
status.setBackgroundResource(R.drawable.offline);
}
}
}
どんな助けでも大歓迎ですありがとう