错误httpclient没有线程运行

时间:2014-03-03 17:26:01

标签: java android

代码:

public boolean CheckDeviceID(final Context context){
    try {
        //Looper.prepare(); //For Preparing Message Pool for the child Thread
        HttpClient httpclient;
        HttpPost httppost;
        ArrayList<NameValuePair> postParameters;
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost("http://"+Server+"/BusTicket/checkdevice/checkdevice.php");

        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber().substring(0, tm.getSimSerialNumber().length()-1);
        Log.d(null,"DeviceID="+tmSerial);
        postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("DeviceID", tmSerial));
        httppost.setEntity(new UrlEncodedFormEntity(postParameters));
        HttpResponse response = httpclient.execute(httppost);
        InputStream in = response.getEntity().getContent(); //Get the data in the entity
        String jsonstring = convertStreamToString(in);
        Log.d(null,"CheckDevice Reponse= "+ jsonstring);
        jsonstring = jsonstring.trim();
        if (jsonstring.equalsIgnoreCase("valid")){
            return true;
        }else{
            return false;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.d(null,"CheckDevice error= "+ e.getMessage());
    }
    //Looper.loop(); //Loop in the message queue
    return false;
}

我有BroadcastReceiver并设置闹钟,每隔10分钟调用一次这个CheckDevice函数,检查这个设备是否在我的数据库中注册,如果这个函数在一个线程中运行,但是不能用线程返回boolean?!?

但如果我使用此功能在OnReceive中运行,将导致错误,我尝试使用e.getMessage打印错误并返回错误null

任何想法运行没有线程的httpclient?或让线程返回布尔值?

更新

我试图使用AsynTask获取返回布尔值,此代码位于OnReceive

new AsyncTask<Void, Void, Boolean>()
                {
                    @Override
                    protected Boolean doInBackground(Void... p)
                    {
                        return CheckDeviceID(context);
                    }

                    @Override
                    protected void onPostExecute(Boolean result)
                    {
                        //this is code for the UI thread, now that it knows what is the result.
                    }
                }.execute();

但是,在这段代码中,如何获得返回布尔值?

1 个答案:

答案 0 :(得分:0)

您必须了解的两条规则: 1-您必须在不同的线程中执行任何网络操作。 2-不要将需要很长时间的代码放在onReceive内,因为接收器的生命周期很短

您将无法返回布尔值但我认为,除其他选项外,您可以使用SharedPreferences或文件来保存线程的结果并在onReceive中检查此SharedPreferences值