当我在单独的线程上运行类(实现Runnable)时,为什么会收到“ android.os.NetworkOnMainThreadException”?

黑谷谷:

在我的应用程序中,我有一个队列,其中包含应发送到服务器的数据库中的项目。由于我希望连续监视此队列,并且由于此任务包括网络通信,因此我创建了一个实现Runnable的类,我将该类称为QueueWorkerThread。但是由于某些原因,我仍然收到“ android.os.NetworkOnMainThreadException”,但我不明白为什么?我曾尝试在SO上搜索类似的问题,但任何接近的问题都在使用AsyncTask,并且由于该类显然将在API级别30中被使用,所以我不想使用它(我希望这个应用程序能够长时间工作)。我的Runnable是否以某种方式在主线程上运行了某些内容?那有可能吗?

这是我的QueueWorker线程的代码:

public class QueueWorkerThread implements Runnable{
private final static String TAG = "QueueWorkerThread";
private AtomicBoolean alive = new AtomicBoolean(true);
private Context mContext;
private FragmentRefreshInterface mFragmentRefreshInterface;
private NetworkStatusInterface mNetworkStatusInterface;

public QueueWorkerThread(Context context, FragmentRefreshInterface fragmentRefreshInterface, NetworkStatusInterface networkStatusInterface) {
    mContext = context;
    mFragmentRefreshInterface = fragmentRefreshInterface;
    mNetworkStatusInterface = networkStatusInterface;
    Log.d(TAG," Thread Started");
}

public void quit(){
    alive.set(false);
}

public void makeReady(){
    alive.set(true);
}

@Override
public void run() {
    SQLiteDatabase database = SQLiteHelper.getSingleton(mContext).getWritableDatabase();
    ServerCommunicationHelper communicationHelper = new ServerCommunicationHelper(mFragmentRefreshInterface,mNetworkStatusInterface);
    while (alive.get()){
        TracerQueueVO tracerQueueVO = SQLiteHelper.getSingleton(mContext).getNextQueueVOFromDatabase(database);

        if(tracerQueueVO.getTracerId()!=null){
            int result = communicationHelper.uploadQueueVO(tracerQueueVO, mContext);
            if(result == ServerCommunicationHelper.UPLOAD_OK){
                SQLiteHelper.getSingleton(mContext).removeQueueVOFromDatabase(database,tracerQueueVO);
            }else{
                SQLiteHelper.getSingleton(mContext).updateQueueVOInDatabase(database,tracerQueueVO);
            }
        }
        try {
            sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

这是MainActivity中启动线程的代码:

private void startQueueWorkerThread(){
    if (mQueueWorkerThread == null){
        mQueueWorkerThread = new QueueWorkerThread(mContext,this, this);
        new Thread(mQueueWorkerThread).start();
    } else {
        mQueueWorkerThread.makeReady();
        mQueueWorkerThread.run();
    }
}

这是我的ServerCommunicationHelper中发生错误的代码:

public int uploadQueueVO(ItemQueueVO queueVO, Context context){
int result = 0;
try {
    String json = queueVO.getData();
    byte[] base64 = Base64.encode(json.getBytes(),0);
    final OkHttpClient CLIENT = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("text/plain; charset=utf8"),base64))
                .build();
        Response response = CLIENT.newCall(request).execute();

        if (response.isSuccessful()){
            result = UPLOAD_OK;
        }else{
            result = UPLOAD_FAILED;
        }

    } catch (Exception e) {
        e.printStackTrace();
        result = UPLOAD_FAILED;
    }
    return result;

这是堆栈跟踪:

W/System.err: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
    at java.net.Socket.connect(Socket.java:621)
    at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:73)
W/System.err:     at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:245)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:165)
W/System.err:     at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
    at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
W/System.err:     at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
W/System.err:     at okhttp3.RealCall.execute(RealCall.java:77)
    at com.xxxxxx.xx.network.ServerCommunicationHelper.uploadQueueVO(ServerCommunicationHelper.java:136)
W/System.err:     at com.xxxxxx.xx.queue.QueueWorkerThread.run(QueueWorkerThread.java:49)
    at com.xxxxxx.xx.MainActivity.startQueueWorkerThread(MainActivity.java:1193)
    at com.xxxxxx.xx.MainActivity.onResume(MainActivity.java:373)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1454)
    at android.app.Activity.performResume(Activity.java:8105)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4529)
W/System.err:     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4572)
    at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:237)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:8016)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1076)
Pavneet_Singh:

在这一else部分中,您将run直接调用将在邮件线程上执行网络调用的方法,因此例外

// this method is being called in onResume so
// second time, mQueueWorkerThread.run will be executed on main thread
private void startQueueWorkerThread(){
    if (mQueueWorkerThread == null){
        mQueueWorkerThread = new QueueWorkerThread(mContext,this, this);
        new Thread(mQueueWorkerThread).start();
    } else {
        mQueueWorkerThread.makeReady();
        mQueueWorkerThread.run(); // it will cause the exception
        // new Thread(mQueueWorkerThread).start(); should use this
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章