问题描述: android.os.NetworkOnMainThreadException异常(不要在主线程访问网络资源)

本文探讨了Android OS NetworkOnMainThreadException异常的原因及解决方案,详细介绍了如何通过忽略强制策略或在独立线程中操作网络资源来解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

android.os.NetworkOnMainThreadException异常(不要在主线程访问网络资源)

问题分析:

造成这种异常的原因是安卓版本问题(仔细研究错误原因是代码不符合Android规范),网上搜索发现:android3.0版本开始(具体是不是从这个版本开始的,就不深究咯)就强制程序不能在主线程中访问网络,要把访问网络放在独立的线程中。

解决方式:

1、想要忽略这些强制策略问题的话,可以在onCreate()方法里面加上

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());


2、放在单独的线程中:(我用的是点击按钮查看网络图片,学习用)

private final class ButtonListenerEvent implements OnClickListener{
@Override
public void onClick(View v) {
    final String path = imagePath.getText().toString();
    final Handler handler = new Handler(){
    public void handleMessage(Message msg){
        switch (msg.what) {
        case 0:
            imageView.setImageBitmap(bitmap);
            break;
        default:
            break;
        }
    }
};
new Thread(){
    public void run(){
    try {
        byte[] data = ImageService.getImage(path);
        // 设置图像的位图
        bitmap = BitmapFactory.decodeByteArray(data, 0,
        data.length);
        //处理完发送一个空消息
        handler.sendEmptyMessage(0);
    } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), R.string.error, 1)
            .show();
            }
        }
    }.start();
    }
}


我做了一个安卓画板app现在添加了一个从url下载图片并设置成画板背板的功能。我把代码给你看,在我输入了https://www.nottingham.edu.cn/image-library/campus-news/signofnottingham.jpg的网站后提示下载失败 /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.edu.nottingham.jianxingwang.fingerpainter; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Stack; /** * Created by pszmdf on 13/10/16. * * Derived from android graphics API sample com.example.android.apis.graphics.Fingerpaint * android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/graphics/FingerPaint.java * */ public class FingerPainterView extends View { private Context context; private Canvas canvas; private Paint paint; private Bitmap bitmap; private Path path; private Uri uri; private Stack<Bitmap> undoStack = new
最新发布
03-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值