Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/193.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ProgressDialog延迟显示,使用AsyncTask的活动延迟_Java_Android_Android Activity_Android Asynctask - Fatal编程技术网

Java ProgressDialog延迟显示,使用AsyncTask的活动延迟

Java ProgressDialog延迟显示,使用AsyncTask的活动延迟,java,android,android-activity,android-asynctask,Java,Android,Android Activity,Android Asynctask,我有一个rpc 2.0服务器,我向它发出请求并得到响应。在onPreExecute方法中,我定义了ProgressDialog和call show方法,在onPostExecute方法中,我调用Disclose ProgressBar,但当我在流程的最后一秒发出请求并显示ProgressDialog时,我的活动会延迟,有人能帮我解决这个问题吗 请求类: public class HomeCommRequest { public static final int ID_GET_MOBIL

我有一个rpc 2.0服务器,我向它发出请求并得到响应。在onPreExecute方法中,我定义了ProgressDialog和call show方法,在onPostExecute方法中,我调用Disclose ProgressBar,但当我在流程的最后一秒发出请求并显示ProgressDialog时,我的活动会延迟,有人能帮我解决这个问题吗

请求类:

public class HomeCommRequest {

    public static final int ID_GET_MOBILE_AUTH_TOKEN = 1;
    public static final int ID_PIN_LOGIN = 2;   
    public static final int ID_GET_ALL_DEVICES_LIST = 3;    
    public static final int ID_GET_DEVICES_LIST = 4;
    public static final int ID_GET_CU_INFO = 5;
    public static final int ID_GET_DEVICE_INFO = 6;
    public static final int ID_GET_USER_INFO = 7;
    public static final int ID_CHANGE_DEVICE_ALARM_STATE = 8;
    public static final int ID_CHANGE_CU_ALARM_STATE = 9;
    public static final String METHOD_GET_USER_INFO = "getUserInfo";
    public static final String METHOD_GET_CU_INFO = "getCentralUnitInfo";
    public static final String METHOD_GET_ALL_DEVICES_LIST = "getAllDevicesList";   
    public static final String METHOD_GET_MOBILE_AUTH_TOKEN = "getMobileAuthToken";
    public static final String METHOD_PIN_LOGIN = "pinLogin";
    public static final String METHOD_GET_DEVICES_LIST = "getDevicesList";
    public static final String METHOD_CHANGE_DEVICE_ALARM_STATE = "changeAlarmState";
    public static final String METHOD_CHANGE_CU_ALARM_STATE = "changeCUAlarmState";
    public static final String METHOD_GET_DEVICE_INFO = "getDeviceInfo";

    private Map<String,Object> params;
    private Context context;
    private int id;
    private String cookie;
    private String method;
    private ProgressDialog dialog;
    private String serverURL = "MY SERVER URL"

    public HomeCommRequest(int id, String method, Map<String,Object> params, String cookie, Context context)
    {
        this.id = id;
        this.method = method;
        this.params = params;
        this.cookie = cookie;
        this.context = context;
    }

    public <T> T send()
    {
        T resp = null;
        doRequest request = new doRequest();
        request.execute();
        try {
            resp = (T) request.get();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resp;
    }



    private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";       
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));      
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) { s += line; }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
        // Return full string
        return s;
    }
    private JSONObject sendRequest(String method, Map<String,Object> params, int id, String cookieToRequest) throws Exception
    {
        String result = null;
        //Packing inputed parameters into second massive for rpc request
        List paramsToSend = new ArrayList();
        paramsToSend.add(params);
        // Creating a new JSON-RPC 2.0 request
        JSONRPC2Request reqOut = new JSONRPC2Request(method, paramsToSend, id);     
        HttpClient client = new DefaultHttpClient();
        //Creating new HttpPost entry for POST request
        HttpPost post = new HttpPost(serverURL);
        if(cookieToRequest != null)
          post.setHeader("Cookie", "sid=" + cookieToRequest);       

        HttpResponse response = null;
        try {
            //Push JSON string in request
            post.setEntity(new StringEntity(reqOut.toJSONString()));
            //Get response from server
            response = client.execute(post);
        } catch (UnsupportedEncodingException e) {          
            e.printStackTrace();        
        }
        catch(Exception e)
        {
            e.printStackTrace();            
        }
        //Get string from respond entry
        HttpEntity entity = response.getEntity();
        InputStream instream = null;
        if (entity != null) {           
            try {
                instream = entity.getContent();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();    
            }
        //Convert respond to string
            result = inputStreamToString(instream);
        Log.i("HomeCommRequest", "Message from server = " + result);    
        }
        return new JSONObject(result);  
    }

    public class doRequest extends AsyncTask<Void, Void, Response>
    {
        @Override
        protected void onPreExecute() {         
            super.onPreExecute();

        dialog = new ProgressDialog(context, ProgressDialog.THEME_HOLO_LIGHT);
            dialog.setMessage("Please, wait...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Response doInBackground(Void... backgroundParams) {

            Response response = null;
            try {
                JSONObject jsonResponseObj = sendRequest(method, params, id, cookie);               

                switch(id)
                {

case ID_PIN_LOGIN: response = new PinLoginResponse(jsonResponseObj);                            

default: Log.e("Request", "Error. doBackground. Invalid id value in switch = " + id);
                }
                publishProgress();

            } catch (Exception e) {             
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(Response result) {
            if(dialog.isShowing())
                dialog.dismiss();

            if(result.hasError())
            {
              AlertDialog.Builder ad = new AlertDialog.Builder(context, AlertDialog.THEME_HOLO_LIGHT);
                ad.setTitle("Error!");
                ad.setMessage(result.getErrorString());
                ad.setPositiveButton("Dismiss", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {}               
                });
                AlertDialog add = ad.create();
                add.show(); 
            }
            super.onPostExecute(result);            
        }

    }

}
以及我如何在活动中使用它:

void getSessionKey(String pincode)
    {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("token", token);
        params.put("pin", pincode);
        HomeCommRequest pinauthRequest = new     HomeCommRequest(HomeCommRequest.ID_PIN_LOGIN,
                                                             HomeCommRequest.METHOD_PIN_LOGIN,
                                                             params,
                                                             null,
                                                             EnterPincodeActivity.this);
        PinLoginResponse getSessionKeyRequest = pinauthRequest.send();
        if(!getSessionKeyRequest.hasError())
        {
            finish();
            Intent tabHostActivityIntent = new Intent(EnterPincodeActivity.this, TabsViewActivity.class);
            tabHostActivityIntent.putExtra("cookie", getSessionKeyRequest.getSessionKey());
            startActivity(tabHostActivityIntent);
        }
void getSessionKey(字符串pincode)
{
Map params=新的HashMap();
参数put(“令牌”,令牌);
参数put(“pin”,pincode);
HomeCommRequest pinauthRequest=新的HomeCommRequest(HomeCommRequest.ID\u PIN\u登录,
HomeCommRequest.METHOD\u PIN\u登录,
params,
无效的
这是一项重要的活动;
PinLoginResponse getSessionKeyRequest=pinauthRequest.send();
如果(!getSessionKeyRequest.hasError())
{
完成();
Intent tabHostActivityIntent=新的Intent(EnterPincodeActivity.this,tabsviewaActivity.class);
tabHostActivityIntent.putExtra(“cookie”,getSessionKeyRequest.getSessionKey());
startActivity(tabHostActivityIntent);
}
正在阻塞UI线程。
您应该在
onPostExecute()
中处理任何响应,而不强制主线程等待
doInBackground()
完成。

调用.get()时,主线程(UI)冻结,因此在doInBackground()之前不会进行图形计算已完成。请尝试一下,您将看到。不能保证在此之前调用onPreExecute()。get()即使它被称为ProgressBar也不会更新。因此,我如何实现服务器请求的进程进度?Runnuble接口是这种情况下的良好选择?AsyncTask很好,您需要从onPostExecute通知您的活动收到了来自服务器的响应。例如,将您的活动作为参数“pinauthRequest.sen”传递d(您的活动);“并将此任务作为一个论据。感谢您的回复!祝您愉快
void getSessionKey(String pincode)
    {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("token", token);
        params.put("pin", pincode);
        HomeCommRequest pinauthRequest = new     HomeCommRequest(HomeCommRequest.ID_PIN_LOGIN,
                                                             HomeCommRequest.METHOD_PIN_LOGIN,
                                                             params,
                                                             null,
                                                             EnterPincodeActivity.this);
        PinLoginResponse getSessionKeyRequest = pinauthRequest.send();
        if(!getSessionKeyRequest.hasError())
        {
            finish();
            Intent tabHostActivityIntent = new Intent(EnterPincodeActivity.this, TabsViewActivity.class);
            tabHostActivityIntent.putExtra("cookie", getSessionKeyRequest.getSessionKey());
            startActivity(tabHostActivityIntent);
        }
resp = (T) request.get();