0

我的应用程序没有给出任何编译时错误,它确实显示了它所显示的活动。这是一个带有按钮的简单活动。当用户点击它时,它应该从网络下载一个图像。当我单击该按钮时,它只是说,“不幸的是,并发已停止。”

我正在阅读 android 中的线程,并且了解了不在 UI 线程中执行密集操作以及不从 UI 线程外部操作 UI 的规则。我正在练习这个。

我还不熟悉如何阅读 logcat。我正在发布我的 logcat,如果有人可以阅读并指出导致问题的原因,那就太好了。

此外,我没有编写 loadImageFromNetwork() 的实现。我只是从网上复制的。所以我不了解它对 decodeStream() 方法的调用。这暂时不是我关心的。

Main.java:-

package com.example.concurrency;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {
    public static final String key_name="com.practice.firstApp.key";
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void downloadImage(){
        new Thread(new Runnable(){

            private Bitmap loadImageFromNetwork(String url){
                try {
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
                return bitmap;
                } catch (Exception e) {
                e.printStackTrace();
                }
                return null;
                }

            public void run(){
                final Bitmap bitmap= loadImageFromNetwork("http://www.google.com/imgres?imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F7%2F7a%2FBasketball.png&imgrefurl=http%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ABasketball.png&h=340&w=340&tbnid=EJmjEDyJzrhAuM%3A&zoom=1&docid=C_hn8nOgsGmuwM&hl=en&ei=Q0o2U93LNcaIygH4mICQBQ&tbm=isch&ved=0CHwQhBwwBg&iact=rc&dur=3875&page=1&start=0&ndsp=14");
                imageView.post(new Runnable(){
                    public void run(){
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }
}

Activity_main.xml:-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity" >

     <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="@string/Button_MainActivity"

        android:onClick="downloadImage"/>

</RelativeLayout>

字符串.xml:-

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Concurrency</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="Button_MainActivity">Download</string>

</resources>

清单.xml:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.concurrency"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.concurrency.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

日志猫:-

它超过了问题的长度。所以你可以在这里找到它。

4

5 回答 5

0

您可以使用 AsyncTask 或以下代码

private Handler mhHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if (msg.what == 100 && msg.obj != null) {
            imageView.setImageBitmap((Bitmap) msg.obj);
        }
    };
};

public void downloadImage(View v) {
    new Thread(new Runnable() {
        private Bitmap loadImageFromNetwork(String url) {
            try {
                Bitmap bitmap = BitmapFactory
                        .decodeStream((InputStream) new URL(url)
                                .getContent());
                return bitmap;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://www.google.com/imgres?imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F7%2F7a%2FBasketball.png&imgrefurl=http%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ABasketball.png&h=340&w=340&tbnid=EJmjEDyJzrhAuM%3A&zoom=1&docid=C_hn8nOgsGmuwM&hl=en&ei=Q0o2U93LNcaIygH4mICQBQ&tbm=isch&ved=0CHwQhBwwBg&iact=rc&dur=3875&page=1&start=0&ndsp=14");
            Message msg = new Message();
            msg.what = 100;
            msg.obj = bitmap;
            mhHandler.sendMessage(msg);
        }
    }).start();
}

并且不要忘记将 View 放在方法 downloadImage(View v) 的参数上,因为您从布局中调用它 onClick 。

于 2014-03-29T14:59:37.247 回答
0

添加

<uses-permission android:name="android.permission.INTERNET" />

还将“View”类型的参数添加到您的 downloadImage 函数中。

于 2014-11-12T22:00:00.567 回答
0

您的 downloadImage 函数需要将 View 作为参数。添加它,它应该修复错误

于 2014-03-29T14:29:18.240 回答
0

您必须在下面添加此行以获得您的应用程序访问 Internet 的权限...

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Activity内部AsynchTask函数的访问方法......

    BitmapWorkerTask backPropcess = new BitmapWorkerTask(position, ht,
                        wt);
                backPropcess.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, urls);

这是一个 asynctask 下载类

            public BitmapWorkerTask() {

                }

                @Override
                protected Bitmap doInBackground(String... params) {
                                    URL url;
                        try {
                            url = new URL(params[0]);

                                HttpURLConnection connection = (HttpURLConnection) url
                                        .openConnection();
                                connection.setConnectTimeout(4000);
                                connection.setReadTimeout(10000);
                                int v = connection.getContentLength() > 0 ? connection
                                        .getContentLength() : 0;

                                    if (v > 0) {
                                        InputStream in = new BufferedInputStream(
                                                connection.getInputStream(), 32 * 1024);
                                        Bitmap bitmap = decodeSampledBitmapFromResource(
                                                in, ht[i], wt[i]);
                                        if (bitmap != null && position != null) {
                                            addBitmapToMemoryCache(position, bitmap);
                                            System.out.println(position);

                            }
                        } catch (MalformedURLException e) {
                            // e.printStackTrace();
                        } catch (IOException e) {
                            // e.printStackTrace();
                        }


                    return bitmap;
                }

                @Override
                protected void onPostExecute(Bitmap result) {
                    imageView.setImageBitmap(result);
                }
               }
于 2014-03-29T14:30:17.923 回答
0
private Bitmap loadImageFromNetwork(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        e.printStackTrace();
        return icon;
    }
}
于 2017-12-11T12:24:23.577 回答