2014-05-25 3 views
0

쿼드 코어 장치의 장점을 활용하기 위해 여러 스레드를로드하려고합니다.Android AsyncTask를 (를) 비동기로 실행할 수 없습니까?

나는 다른 URL에서 JSON 파일을 다운로드 할 비동기 작업과 많은 스레드를로드하려합니다.

내가 지금 직면 한 문제는 얼마나 많은 비동기 작업 (1 ~ 5)을 스핀 오프 할 수 있더라도 올바르게 스핀 오프 할 수 있지만 ThreadPoolExecutor가 runWorker (Worker)를 실행하려고하면 오류가 발생합니다.

그것은 첫째 AsyncTask를 # 1 여기를 실행 충돌하는
final void runWorker(Worker w) { 
    Thread wt = Thread.currentThread(); 
    Runnable task = w.firstTask;![enter image description here][1] 
    w.firstTask = null; 
    w.unlock(); // allow interrupts 
    boolean completedAbruptly = true; 
    try { 
     while (task != null || (task = getTask()) != null) { 
      w.lock(); 

^^^ , 이해가되지 않는 이유

변수 :

enter image description here

ThreadGroup를 클래스의 캐치되지 않는 예외는

public void uncaughtException(Thread t, Throwable e) { 
    if (parent != null) { 
     parent.uncaughtException(t, e); 
    } else if (Thread.getDefaultUncaughtExceptionHandler() != null) { 
     // TODO The spec is unclear regarding this. What do we do? 
     Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t, e); 
    } else if (!(e instanceof ThreadDeath)) { 
     // No parent group, has to be 'system' Thread Group 
     e.printStackTrace(System.err); 
    } 
} 

More Variables in the exception

이것은 내가 작업을 시작하는 방법입니다

private void startMyTask(AsyncTask asyncTask, String[] param) { 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) 
     asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, param); 
    else 
     asyncTask.execute(param); 

OK 로그 고양이 스택 추적

enter image description here

AsyncTask를 서브 클래스

package data; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.security.KeyManagementException; 
import java.security.KeyStore; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.cert.CertificateException; 

import javax.net.ssl.HostnameVerifier; 
import javax.net.ssl.HttpsURLConnection; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.SSLSession; 
import javax.net.ssl.TrustManagerFactory; 

import org.xmlpull.v1.XmlPullParserException; 
import framework.QoowayActivity; 
import android.os.AsyncTask; 
import android.util.Log; 

public class HttpRequestTask extends AsyncTask<String, Void, String> { 

private QoowayActivity activity; 
private Boolean Xml = false; 
private EnumData.request_mode rm; 
private status stat= status.notLoggedIn; 
private String loginToken = "QoowayMember"; 
private DataStorageManager dataStorageManager = DataStorageManager.getSingletonInstance(); 
private String dataType; 

public HttpRequestTask(QoowayActivity activity, EnumData.request_mode rm) { 
    this.activity = activity; 
    this.rm = rm; 
    this.dataType =dataStorageManager.getTempKey(); 

} 


// 
public HttpRequestTask(QoowayActivity activity, Boolean xml) { 

    this.activity = activity; 
    this.Xml = xml; 

} 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     DataStorageManager.getSingletonInstance().incrementAsyncTask(); 
     /* 
     if(!DataStorageManager.getSingletonInstance().checkInActivity) { 
      DataStorageManager.getSingletonInstance().incrementAsyncTask(); 
     } 
     */ 
    } 

@SuppressWarnings("finally") 
@Override 
protected String doInBackground(String... urls) { 

    // params comes from the execute() call: params[0] is the url. 
    String result = null; 

    try { 

     result = loadResult(urls[0]); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return result; 

} 

// onPostExecute displays the results of the AsyncTask. 
@Override 
protected void onPostExecute(String result) { 
    DataStorageManager dataStorageManager = DataStorageManager.getSingletonInstance(); 
    dataStorageManager.decrementAsyncTask(); 
    /* 
    if(!dataStorageManager.checkInActivity) { 
     dataStorageManager.decrementAsyncTask(); 
    } 
    */ 
    if(this.rm == EnumData.request_mode.LogIN) 
    { 
     if (this.stat== status.loggedIn) { 
      dataStorageManager.loggedIn = true; 
     } else { 
      dataStorageManager.loggedIn = false; 
     } 
    } 
     super.onPostExecute(result); 

    //activity.cancelProgressDialog(); 
    //REMOVE 

} 


@SuppressWarnings("unchecked") 
private String loadResult(String urlString) throws XmlPullParserException, 
     IOException { 
    InputStream stream = null; 
    String result = null; 
    try { 
     stream = downloadUrl(urlString); 
     result = inputStreamToString(stream); 
     // Makes sure that the InputStream is closed after the app is 
     // finished using it. 
    } catch (Exception e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    if (stream != null) { 
     stream.close(); 
    } 
    return result; 

} 

private InputStream downloadUrl(String urlString) throws IOException, 
     KeyManagementException, NoSuchAlgorithmException, 
     KeyStoreException, CertificateException { 

    DataStorageManager dataStorageManager = DataStorageManager.getSingletonInstance(); 
    String userName = dataStorageManager.userName; 
    String passWord = dataStorageManager.password; 
    HttpURLConnection conn = null; 
    if (urlString.startsWith("https")) { 
     try { 
      conn = (HttpURLConnection) httpsConnection(urlString); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } else { 
     URL url = new URL(urlString); 
     conn = (HttpURLConnection) url.openConnection(); 
    } 
    conn.setReadTimeout(10000 /* milliseconds */); 
    conn.setConnectTimeout(15000 /* milliseconds */); 
    conn.setRequestMethod("GET"); 
    conn.setDoInput(true); 
    if (Xml) { 
     conn.setRequestProperty("Accept", "text/xml"); 
    } 

    if(dataStorageManager.loggedIn) { 
     conn.setRequestProperty(
       "Authorization", dataStorageManager.loginToken);  
    } else { 
    conn.setRequestProperty(
      "Authorization", loginToken); 
    } 
     /* "Basic " 
        + Base64.encodeToString(
          ((userName + ":" + passWord).getBytes()), 
          Base64.NO_WRAP)); */ 

    // Starts the query 
    conn.connect(); 

    int code = conn.getResponseCode(); 
    String message = conn.getResponseMessage(); 
    dataStorageManager.lastCode = code; 
    if(!message.isEmpty()){ 
     dataStorageManager.lastMessage = message; 
    } 

    if(code < 200 || code > 299) { 
     activity.showDialog(); 
    } 

    Log.i("WebApi", ""+code); 
    //activity.showDialog(); 


    String temp =conn.getResponseMessage(); 
    if(conn.getResponseMessage().equals("OK") && this.rm == EnumData.request_mode.LogIN) 
    { 
     this.stat = status.loggedIn; 
    } 
    return conn.getInputStream(); 
} 

private HttpURLConnection httpsConnection(String urlString) 
     throws NoSuchAlgorithmException, KeyManagementException, 
     KeyStoreException, IOException, CertificateException { 
    HostnameVerifier hostnameVerifier = new HostnameVerifier() { 
     @Override 
     public boolean verify(String hostname, SSLSession session) { 
      HostnameVerifier hv = HttpsURLConnection 
        .getDefaultHostnameVerifier(); 
      return hv.verify(HttpRequestTask.this.getHostName(), session); 
     } 
    }; 
    // Get an instance of the Bouncy Castle KeyStore format 
    KeyStore trusted = KeyStore.getInstance("BKS"); 
    // Get the raw resource, which contains the keystore with 
    // your trusted certificates (root and any intermediate certs) 
    InputStream in = activity.getApplicationContext().getResources() 
      .openRawResource(this.getKeyStore()); // took away 2 
    try { 
     // Initialize the keystore with the provided trusted 
     // certificates 
     // Also provide the password of the keystore 
     trusted.load(in, this.getKeyStorePassWord().toCharArray()); 
    } finally { 
     in.close(); 
    } 
    String algorithm = TrustManagerFactory.getDefaultAlgorithm(); 
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); 
    tmf.init(trusted); 

    SSLContext context = SSLContext.getInstance("TLS"); 
    context.init(null, tmf.getTrustManagers(), null); 

    URL url = new URL(urlString); 
    HttpsURLConnection urlConnection = (HttpsURLConnection) url 
      .openConnection(); 
    urlConnection.setSSLSocketFactory(context.getSocketFactory()); 
    urlConnection.setHostnameVerifier(hostnameVerifier); 
    return urlConnection; 
} 

private String inputStreamToString(InputStream is) throws IOException { 
    String line = ""; 
    StringBuilder total = new StringBuilder(); 

    // Wrap a BufferedReader around the InputStream 
    BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

    // Read response until the end 
    while ((line = rd.readLine()) != null) { 
     total.append(line); 
    } 

    // Return full string 
    return total.toString(); 
} 

private enum status 
{ 
    loggedIn , notLoggedIn 
} 

private int getKeyStore() 
{ 
    return DataStorageManager.getSingletonInstance().getApiKeyStore(); 
} 

private String getHostName() 
{ 
    return DataStorageManager.getSingletonInstance().getApiHostNameVerfier(); 
} 

private String getKeyStorePassWord() 
{ 
    return DataStorageManager.getSingletonInstance().getKeyStorePassword(); 
} 

} 당신의 스택 트레이스에서

+0

어떤 오류입니까? 무슨 예외? 무슨 사고? logcat/stacktrace를 게시하십시오. – indivisible

+0

AsyncTask 하위 클래스의 코드를 게시하십시오. – matiash

+0

감사 얘들 아, 나는 고양이와 스택 트레이스를 기록, 하위 클래스를 추가 한 – noobiehacker

답변

0

:

Caused by java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[] 
at data.HttpRequestTask.doInBackground... 

찾아 제대로 인수를 구문 분석/캐스팅 다시 방법을 따라 추적을 따르십시오. 향후

텍스트의 스크린 샷을 사용하지 않는 시도, 그것이 더 어렵게하기 위해 많은도 그것 때문에 시도하지 않을 수 있습니다.

관련 문제