Je veux créer une application sous Android qui analyse tous les réseaux toutes les 5 secondes. Pour pouvoir tous les réseaux à plusieurs reprises, j'utilise handler.postDelayed. Les fonctions task()
et wi()
doivent être exécutées. task()
semble fonctionner, mais pas wi()
. Une idée pourquoi?handler.postDelayed n'exécute pas
public class MainActivity extends Activity {
TextView tv , tv2;
int i = 0 ;
Timer t;
Thread time;
Handler handler;
WifiManager wifi;
WifiScanReceiver wifiReciever;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
handler = new Handler();
handler.postDelayed(new Runnable() { public void run() { task();}}, 5000);
}
public void task(){
i++;
tv.setText("Values "+i);
wi();
}
public void wi(){
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
wifi.startScan();
}
protected void onPause() {
unregisterReceiver(wifiReciever);
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class WifiScanReceiver extends BroadcastReceiver{
public void onReceive(Context c, Intent intent) {
WifiInfo ws = wifi.getConnectionInfo();
tv2.setText(ws.toString());
}
}
}
sortie: valeur 1
Je suis allé appeler la fonction wi() dans la tâche après toutes les 5s mais wi() ne montre rien –
@UsmanMustafa Avez-vous inclus les bonnes permissions? Regardez [cette réponse] (http://stackoverflow.com/a/7808715/5260943) et vérifiez le modifier à ma réponse –
oui j'ai ajouter ces autorisations dans le fichier manifeste quand je n'utilise pas handler cela fonctionne parfaitement mais appelez wi() dans la tâche ne fonctionne pas –