从AsyncTask显示Toast直到事件发生

时间:2015-05-31 20:12:32

标签: android android-asynctask toast

我想使用Toast 显示“正在连接...”,直到设备连接到新网络(更具体地说,获取IP地址时,请参阅下面的doInBackground中的while循环) 。我正在使用AsyncTask连接到网络,但是如果我在onProgressUpdate()中放置Toast.makeText(...)。show(),那么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);
    }
}

3 个答案:

答案 0 :(得分:2)

我建议使用ProgressDialog代替Toast。您可以在运行AsyncTask之前显示它并隐藏它onPostExecute。它看起来像.-

ProgressDialog dialog = ProgressDialog.show(CurrentActivity.this, "", "Connecting...", true, false);

[...]

dialog.dismiss();

顺便说一句,不要忘记将您的字符串文字放在Strings资源文件中:)

答案 1 :(得分:0)

Toast不是展示进展工作的好方法。 Toast旨在显示次要和快速的信息(例如,在您的情况下是为了表明设计是连接的),但在我看来,最好在布局中实现ProgressBar并在AsyncTask时将其设置为可见执行doInBackground并在onPostExecute中将其设置为不可见。

答案 2 :(得分:0)

如果你需要在另一个线程中显示Toast,也在doInBackground(Object ... params)中,你可以使用:

YourActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        //put here your thread
    }
});

Hovewer,在这种情况下你需要获得Context。我使用静态变量。但不要忘记,Toast只出现在短时间内,你无法管理它。如果您需要随时显示消息,可以使用ProgressDialog