我想用Toast顯示「Connecting ...」直到設備連接到一個新網絡(更具體地說,當獲得IP地址時,請參閱doInBackground中的while循環下面)。我使用的AsyncTask用於連接到網絡,但如果我把Toast.makeText(...)。裏面onProgressUpdate秀()()的調用敬酒堆棧會,並最終顯示長於所需文本的方式。我的連接類:從AsyncTask顯示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);
}
}
這恐怕是不可行與吐司。相反,更常見的做法是展示一個微調器,例如,您可以顯示並隱藏需要的地方。 – harism
@harism它應該是。做一個最後的私人吐司並使用該文本。在onProgressUpdate要調用.show(),然後在onPostExecute調用.cancel()。我現在在打電話,所以我沒有嘗試,但給了一個鏡頭。雖然,是的,一個微調可能會更好 –