我想使用 Toast 显示“正在连接...”直到设备连接到新网络(更具体地说,当获得 IP 地址时,请参见下面 doInBackground 中的 while 循环) .我正在使用 AsyncTask 连接到网络,但是如果我将 Toast.makeText(...).show() 放在 onProgressUpdate() 中,toast 调用将堆叠并最终以比预期更长的时间显示文本。我的连接类:
public class Connect extends AsyncTask<Object,Void,Void>{
private static final String TAG="sure2015test";
private Context context;
private Network network;
@Override
protected Void doInBackground(Object... params) {
this.network=(Network)params[0];
this.context=(Context) params[1];
final WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + network.ssid + "\"";
if(network.password!=null){
conf.preSharedKey = "\""+ network.password +"\"";
}
else{
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
if(network.manager.addNetwork(conf)==-1){
Log.i(TAG, "Add network fail");
}
List<WifiConfiguration> configs = network.manager.getConfiguredNetworks();
for (WifiConfiguration i : configs) {
if (i.SSID != null && i.SSID.equals("\"" + network.ssid + "\"")) {
network.manager.disconnect();
if(network.manager.enableNetwork(i.networkId, true)==false){
Log.i(TAG,"Enable Network fail ");
}
if(network.manager.reconnect()==false) {
Log.i(TAG, "Reconnect fail");
}
}
}
WifiInfo info=network.manager.getConnectionInfo();
while((info.getIpAddress())==0){
//Wait until non-zero IP address (once a non-zero ip address is obtained, you are connected to the network)
//Tried to use NetworkInfo.DetailedState to check if it was CONNECTED
//However the api method said it remained in OBTAINING_IPADDR state even after it obtained an ip (must be bug)
info=network.manager.getConnectionInfo();
publishProgress();
Log.i(TAG,"IP "+info.getIpAddress());
try{
Thread.sleep(100);
}
catch(InterruptedException e){
Log.i(TAG,"Interrupted exception");
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
Toast.makeText(context, "Connecting ...", Toast.LENGTH_SHORT).show();
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(context,"Connected",Toast.LENGTH_SHORT).show();
Intent newActivity = new Intent(context, Device.class);
newActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newActivity.putExtra("Device", network.ssid);
context.startActivity(newActivity);
super.onPostExecute(aVoid);
}
}
最佳答案
我建议使用 ProgressDialog而不是 Toast
。您可以在运行 AsyncTask
之前显示它并在 onPostExecute
中隐藏它。它看起来像。-
ProgressDialog dialog = ProgressDialog.show(CurrentActivity.this, "", "Connecting...", true, false);
[...]
dialog.dismiss();
顺便说一句,不要忘记将您的字符串字面值放入 Strings
资源文件中 :)
关于android - 从 AsyncTask 显示 Toast 直到事件发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562182/