Java httpclient在没有线程的情况下运行时出错 代码:
但是,在这段代码中,如何获取返回布尔值?您必须了解以下两条规则: 1-您必须在不同的线程中执行任何网络操作。 2-不要将花费很长时间的代码放在onReceive中,因为接收器的寿命很短Java httpclient在没有线程的情况下运行时出错 代码:,java,android,Java,Android,但是,在这段代码中,如何获取返回布尔值?您必须了解以下两条规则: 1-您必须在不同的线程中执行任何网络操作。 2-不要将花费很长时间的代码放在onReceive中,因为接收器的寿命很短 您将无法返回布尔值,但我认为,在其他选项中,您可以使用SharedReferences或文件来保存线程的结果,并在onReceive中检查此SharedReferences值。您需要研究AsyncTask。这就是你想要的:@LokiSinclair是的,我知道,我也做了,但是@LokiSinclair更新代码失败
您将无法返回布尔值,但我认为,在其他选项中,您可以使用
SharedReferences
或文件来保存线程的结果,并在onReceive中检查此SharedReferences值。您需要研究AsyncTask。这就是你想要的:@LokiSinclair是的,我知道,我也做了,但是@LokiSinclair更新代码失败了,请检查这是一个好的开始,但是你现在需要实现onTaskCompleteListener(或者类似的东西-我不在电脑上),然后重写onTaskComplete函数来检索你的布尔值。:)不要在接收上花费很长时间,但我有一个关于stackflow的问题,他们要求我将Broadreceive与AlarmManager一起使用。因为在这个broadreceive中我正在进行同步如果不使用broadreceive,有什么更好的方法让同步工作直到设备关闭?你搞错了。在您的情况下使用广播接收器是合适的,我的意思是当您在onReceive()方法中接收时要执行的操作。如果需要很长时间,那么像现在一样在onReceive中使用线程。在运行线程之前,您是否尝试将结果保存在SharedReferences中并在onReceive中进行检查?下次调用onreceive时,它应该检查此值,并仅在未设置该值时启动线程。是的,我知道SharedReferences方法,但我认为这不是我的首选答案,我希望使用AsyncTask,但我不知道如何获取返回的布尔值
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;
}
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();