httpclient在执行时休眠

时间:2013-02-07 17:32:53

标签: android timeout httpclient wakelock

我正在开发长时间运行的应用程序,我的应用程序定期使用DefaultHttpClient(我也尝试使用AndroidHttpClient)。我不知道,但在工作了一段时间后,不知怎的httpClient.execute睡了。字面上睡觉,当我醒来(解锁或连接到PC)时,我的设备httpClient立即继续工作(如果我设置超时或仅返回执行的响应则抛出异常)。我搜索并尝试了类似的案例和非工作。对于wake和wifilocks,我只是在执行前获取wifi锁和唤醒锁,并在获得响应后释放它。什么都行不通,我没有理想。

我工作的设备是Galaxy S3(v4.0 +)和Ace(v2.3.6)

提前感谢。

这是MyTask卡住了,它停留在response = new MyClient(ctx).client.execute(post);行,而MyClient是一个包装器,以便处理https&证书事。

public abstract class GenericTask extends AsyncTask<Object, Object, Document> {


public final static String TAG = "GenericTask";
private WakeLock wakeLock;
private WifiLock wifiLock;
protected HttpPost post;
public String taskId;
public Context ctx;
Object parameter;

public GenericTask(Context ctx, Object parameter) {
    this.parameter = parameter;
    this.ctx = ctx;
    post = null;
    initLock(ctx);
    lock();
}
private void lock() {
    try {
        wakeLock.acquire();
        wifiLock.acquire();
        Log.d(TAG,"LockAcquired");
    } catch (Exception e) {
        Log.e("WlanSilencer", "Error getting Lock: " + e.getMessage());
    }
}

private void unlock() {
    Log.e(TAG,"unlock");
    if (wakeLock.isHeld())
        wakeLock.release();
    if (wifiLock.isHeld())
        wifiLock.release();
    Log.d(TAG,"LockReleased");
}

private void initLock(Context context) {
    wifiLock = ((WifiManager) context
            .getSystemService(Context.WIFI_SERVICE)).createWifiLock(
            WifiManager.WIFI_MODE_FULL_HIGH_PERF, "GenericTaskWifiLock");
    wakeLock = ((PowerManager) context
            .getSystemService(Context.POWER_SERVICE)).newWakeLock(
            PowerManager.FULL_WAKE_LOCK, "GenericTaskWakeLock");
    Log.d(TAG,"LockInitiated");
}

public boolean cancelTask(boolean bln) {
    if(post!=null)
        post.abort();
    return super.cancel(bln);
}

public void execute(){
    if(Build.VERSION.SDK_INT >= 11){
        startNew();
    }else{
        startOld();
    }
}
private void startOld() {
    super.execute();

}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void startNew(){
    executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
@Override
protected void onPostExecute(Document doc) {
    unlock();
    if(doc==null){
        Log.e("GenericTask: " +getClass(),"onPostExecute doc=null");
    }
    Log.e(TAG,"onPostExecute");
        TaskManager.getInstance().returnFromTaskSuccess(doc, getClass(), taskId, parameter);

}

@Override
protected Document doInBackground(Object... params) {
    Log.e(TAG,"doInBackground");
    try {
        return call();
    } catch (InvalidKeyException e) {
        OtherUtils.printStackTrace(e);
    } catch (NoSuchPaddingException e) {
        OtherUtils.printStackTrace(e);
    } catch (InvalidAlgorithmParameterException e) {
        OtherUtils.printStackTrace(e);
    } catch (IllegalStateException e) {
        OtherUtils.printStackTrace(e);
    } catch (NoSuchAlgorithmException e) {
        OtherUtils.printStackTrace(e);
    } catch (IOException e) {
        OtherUtils.printStackTrace(e);
    } catch (TransformerException e) {
        OtherUtils.printStackTrace(e);
    } catch (ParserConfigurationException e) {
        OtherUtils.printStackTrace(e);
    }
    return null;
}
protected abstract String getUrl();

protected abstract Document getRequest();

public int initialSleep() {
    return 0;
}

public String getTaskId() {
    return taskId;
}

public void setTaskId(String taskId) {
    this.taskId = taskId;
}

protected Document call() throws IOException, TransformerException, ParserConfigurationException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalStateException, NoSuchAlgorithmException{


Document doc = getRequest();
    String url = getUrl();
    Document responseXml = null;
    try {

        post = HttpUtils.postXml(doc, url, null);

        HttpResponse response;
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 16000);
        HttpConnectionParams.setSoTimeout(httpParams, 20000);
        post.setParams(httpParams);
        response = new MyClient(ctx).client.execute(post);
        HttpEntity resEntity = response.getEntity();
        responseXml = XmlUtils.entityToXml(resEntity, null);
        resEntity.consumeContent();
        return responseXml;
    } catch (TransformerException e) {
        throw e;
    } catch (IOException e) {
        throw e;
} 


}
}

HttpUtils:

public class HttpUtils {
public static HttpPost postXml(Document doc, String url, WrapperAsByteArrayOutputStream baos) throws IOException, TransformerConfigurationException, TransformerException
{
    StringWriter xmlAsWriter = new StringWriter();
    StreamResult result = new StreamResult(xmlAsWriter);
    TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), result);
    HttpPost post = new HttpPost(url);
    InputStreamEntity req;
    if ( baos == null ) {
        req = new InputStreamEntity(new ByteArrayInputStream(xmlAsWriter.toString().getBytes()), -1);
    }
    else {
        req = new InputStreamEntity(new WrappedInputStream(new ByteArrayInputStream(xmlAsWriter.toString().getBytes()), baos), -1);
    }
    req.setChunked(true);
    post.setEntity(req);
    return post;
}

MyClient:

public class MyClient扩展DefaultHttpClient {     公共HttpClient客户端;

public MyClient(Context ccc) {
    super();
    KeyStore localTrustStore = null;
    try {
        localTrustStore = KeyStore.getInstance("BKS");
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
    InputStream in = ccc.getResources().openRawResource(
            R.raw.localcert);
    try {
        localTrustStore.load(in, "local_trust_password".toCharArray());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory
            .getSocketFactory(), 80));
    SSLSocketFactory sslSocketFactory = null;
    try {
        sslSocketFactory = new SSLSocketFactory(localTrustStore);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params,
            schemeRegistry);

    this.client = new DefaultHttpClient(cm, params);
}

了解AlarmReciever

public void onReceive(Context context, Intent intent) {
    try {
        TaskManager.getInstance().sendBatteryStatus();
         }
    } catch (Exception e) {
        Toast.makeText(
                context,
                "There was an error somewhere, but we still received an alarm",
                Toast.LENGTH_SHORT).show();
        e.printStackTrace();

    }

returnfromtask成功只需检查id是否有线程安全,处理doc并设置如下所示的新警报:

 Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 30);
    Intent intent = new Intent(ctx, AlarmReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(ctx, 2131225, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager) ctx
            .getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

sendBatteryStatus获取一些要发送的信息,并将其传递给扩展GenericTask的任务,它通常执行new MyAsyncTask(..bla bla).execute();

1 个答案:

答案 0 :(得分:0)

一旦释放唤醒锁定,CPU就会被允许进入睡眠状态,这很可能发生了什么。您使用HttpClient多次执行操作,但在某些时候,在释放唤醒锁定后,CPU会休眠。

由于您希望定期执行代码,因此应使用此处记录的AlarmManager服务:http://developer.android.com/reference/android/app/AlarmManager.html。即使手机处于睡眠状态,警报管理器服务仍处于活动状态。您可以通过PendingIntent方法之一安排AlarmManager.set*()来使用它。警报管理器将在接收器onReceive()方法的持续时间内保持唤醒锁定,但您很可能需要获取WiFi锁定。