我有一個應用程序,它聽指示的IP和端口。我瞭解如何連接,如何接收數據。很難理解wifi連接如何工作
的事情是:
- 我不知道如何來確認連接是否SUCESSFUL
- 我不明白如何檢測連接丟失
- 我不瞭解如何退出我的AsyncTask當我離開的應用程序(使用菜單)
這裏是用於獲取DATAS我的課:
public final class MyClientTask extends AsyncTask<Void, Void, Void> {
BufferedReader br = null;
String dstAddress;
int dstPort;
String response = "";
public MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
@Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
//Instanciation de l'inputStreamReader
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
// creation nouveau bufferreader
br = new BufferedReader(inputStreamReader);
StringBuilder msgBuilder = new StringBuilder();
// on évite String = String + char qui fait des créations de builders automatiques en java.
boolean ended = false;
while (!ended) {
int nextChar = inputStreamReader.read();
if (nextChar == -1) {
ended = true; // <= fin du stream
} else if (nextChar == 03) {
String maChaine="";
// fin du message
maChaine = msgBuilder.toString();
//récupération du char après <STX>
Character nbChamps = maChaine.charAt(1);
//test pour savoir si c'est une alerte
if(nbChamps == '7'){
//insertion de l'alerte dans la BDD
BDDAlerte.insertAlerte1(maChaine);
//creation de la notif
createNotification();
}
//ici les tests splits pour le nombre de champs et inserer dans BdD ou faire ce qu'il faut
//suppVieillesAlertes();
runOnUiThread(new Runnable() {
@Override
public void run() {
//find listview to populate
final ListView lvItems = (ListView)findViewById(R.id.listView1);
//setup cursor adapter using Cursor from last step
final AlerteAdapter todoAdapter = new AlerteAdapter(getBaseContext(), BDDAlerte.getAllRows(),0);
lvItems.setAdapter(todoAdapter);
}
});
// réinitialisation du builder
msgBuilder.setLength(0);
} else {
msgBuilder.append((char)nextChar);
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
}
我退出按鈕位於我的應用程序的菜單中onOptionsItemSelected。
如果我沒有給出所有的數據,我在這裏要清理一些事情。
西蒙