如何使用来自android中不同活动的进度条的异步任务

时间:2016-03-30 09:45:19

标签: android exception android-asynctask downloading

我在这个项目中使用了elasticView进度条库。当我在一个GlobalWindow中使用Activity直接使用它时,它工作正常,但是当我创建新的java类以供下载并从AsyncTask访问时。它显示了类未找到的异常。这是我的错误日志的完整代码。

MainActivity

MainActivity

download.java

public class MainActivity extends AppCompatActivity {
    Button b1;

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

        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download d=new download();
                d.startdownload();
            }
        });
    }

activity_main.xml中

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import it.michelelacorte.elasticprogressbar.ElasticDownloadView;

public class download extends AppCompatActivity {
    ElasticDownloadView mElasticDownloadView;

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

        mElasticDownloadView = (ElasticDownloadView) findViewById(R.id.elastic_download_view);
        mElasticDownloadView.setVisibility(View.VISIBLE);

        startdownload();
    }

    public void startdownload() {

        final DownloadTask downloadTask = new DownloadTask(download.this);
        mElasticDownloadView.setVisibility(View.GONE);
        downloadTask.execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg");
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        private Context context;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {


            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }

                int fileLength = connection.getContentLength();
                input = connection.getInputStream();
                output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {

                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;

                    if (fileLength > 0) {
                        int status = ((int) (total * 100 / fileLength));
                        publishProgress(status);
                    }
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mElasticDownloadView.startIntro();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mElasticDownloadView.setProgress(10);
        }

        @Override
        protected void onPostExecute(String result) {
            mElasticDownloadView.success();
            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        }
    }
}

elastic.xml

 <?xml version="1.0" encoding="utf-8"?>
    <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"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="net.logicalsteps.download_notif.MainActivity">

        <include layout="@layout/elastic"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="start download"
            android:id="@+id/button"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="31dp" />
    </RelativeLayout>

错误日志:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <it.michelelacorte.elasticprogressbar.ElasticDownloadView
        android:id="@+id/elastic_download_view"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="27dp" />



</RelativeLayout>

3 个答案:

答案 0 :(得分:2)

您需要使用Activity从另一个人Intent开始,否则您的课程将被初始化,但Activity将无法启动其生命周期(onCreate方法等不会被调用):

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent downloadIntent = new Intent(v.getContext(), download.class);
            startActivity(downloadIntent);
        }
    });

如果您不想打开新的Activity,可以将AsyncTask移至MainActivity,在下载时,您可以展示自定义{ {1}} {1}} {1}}。您可以在此here找到更多信息。

答案 1 :(得分:1)

只需要看一下

 download d=new download();
 d.startdownload();

您调用了startdownload()方法,但直到那时onCreate download活动未被调用,因此无法初始化mElasticDownloadView。因此,无论是在startdownload方法中,还是在您认为合适的任何地方,都要初始化,或者在download方法中启动活动onClick()

答案 2 :(得分:0)

错误原因

发生这种情况的原因是,当系统启动download活动时,它会执行设置download.onCreate的{​​{1}}。但是,当您在mElasticDownloadView = ...中创建时,不会调用onClick,因此onCreate未初始化。

使用活动

现在在mElasticDownloadView中,您可以创建onClick活动的实例:

download

这不是创建活动的常用方法。如果你这样做,活动将不会从布局XML文件中释放所有UI,因此也没有进度条。如果要显示活动,则应使用:

download d=new download();
d.startdownload();

现在,如果您想将消息传递给Activity,您可以通过intent传递它:

Intent intent = new Intent(MainActivity.this, download.class);
startActivity(intent);

然后在intent.putExtra(EXTRA_MESSAGE, message); 中,您可以检索此消息download.onStart

但是,在您的getIntent().getStringExtra(...)中,无论如何都要拨打download.onCreate,因此您不需要传递消息。

点击此处了解详情:https://developer.android.com/training/basics/firstapp/starting-activity.html