我不完全確定如何解釋這個,但即時通訊新的AsyncTask和im試圖做的是發送UDP數據包到我的服務器,如果我得到一個答覆它設置它如果不是它的離線,則在線。現在,它在第一次打開應用程序時正常工作,但是一旦加載了新頁面,它表示服務器即使在線時仍處於脫機狀態。我不知道它有什麼問題。我是否正確執行AsyncTask或某種程度?這是我能想到的唯一的事情。Android的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);
}
}
}
任何幫助是非常讚賞的感謝
爲什麼你有兩個'檢查()'函數在兩個不同的地方?而在你的代碼中,你甚至沒有使用'CheckStatusTask' ......那麼爲什麼還有'main()'方法呢? Android不會運行'main()' –
woops對不起,我發佈了錯誤的文件爲我的main.java生病編輯它。編輯它以獲得正確的文件。 – Adonai
現在我看到了正確的文件:)但是我可能會問,爲什麼'Main'擴展'ActionBar'而不是比如說'Activity'? –