在 Android 中尝试使用 IntentService 下载图像时失败

Image download failed when try to download by using IntentService in Android

我正在尝试使用 AsynckTask 下载图像,但它没有提供图像。只要我保持应用程序但不加载图像,我的 ProgressBar 就会显示进度。

这是我的应用程序的 UI 设计:

主要活动:

Java

public class MainActivity extends AppCompatActivity {
    ImageView img;
    Button btn;
    EditText edt;
    ProgressBar prb;
    SampleResultReceiver sampleResultReceiver;
    String defalut_url="http://9xmobi.com/image/15580/size/128x128/KAJOL(12)%5B9xmobi.com%5D.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        img=(ImageView)findViewById(R.id.image_view);
        setContentView(R.layout.activity_main);
        edt=(EditText)findViewById(R.id.urlid);
        btn=(Button)findViewById(R.id.button);
        prb=(ProgressBar)findViewById(R.id.progress);
    }
    public void click(View view){
        Intent intent=new Intent(MainActivity.this,MyIntentServiceActivity.class);
        intent.putExtra("receiver",sampleResultReceiver);
        intent.putExtra("url", TextUtils.isEmpty(edt.getText())?defalut_url:edt.getText().toString());
        startService(intent);
        prb.setVisibility(View.VISIBLE);
        prb.setIndeterminate(true);
    }
    class SampleResultReceiver extends ResultReceiver {
        /**
         * Create a new ResultReceive to receive results.  Your
         * {@link #onReceiveResult} method will be called from the thread running
         * <var>handler</var> if given, or from an arbitrary thread if null.
         *
         * @param handler
         */
        public SampleResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            switch (resultCode){
                case MyIntentServiceActivity.DOWNLOAD_ERROR:
                    Toast.makeText(getApplicationContext(), "error in download",
                            Toast.LENGTH_SHORT).show();
                    prb.setVisibility(View.INVISIBLE);
                    break;
                case MyIntentServiceActivity.DOWNLOAD_SUCCESS:
                    String file_path=resultData.getString("file_path");
                    Bitmap bmp= BitmapFactory.decodeFile(file_path);
                if (img!=null&&bmp!=null){
                    img.setImageBitmap(bmp);
                    Toast.makeText(getApplicationContext(),
                            "image download via IntentService is done",
                            Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(getApplicationContext(),
                            "error in decoding downloaded file",
                            Toast.LENGTH_SHORT).show();
                }
                    prb.setIndeterminate(false);
                    prb.setVisibility(View.INVISIBLE);

                    break;

            }
            super.onReceiveResult(resultCode, resultData);
        }
    }
}

我的服务 Class 是...

Java

public class MyIntentServiceActivity extends IntentService {
    public static final int DOWNLOAD_ERROR=10;
    public static final int DOWNLOAD_SUCCESS=11;
    int byteCount=0;
    public MyIntentServiceActivity(){
        super(MyIntentServiceActivity.class.getName());

    }
    @Override
    protected void onHandleIntent(Intent intent) {
        String path=intent.getStringExtra("url");
        final ResultReceiver receiver=intent.getParcelableExtra("receiver");
        Bundle bundle=new Bundle();
        File internal_root= Environment.getExternalStorageDirectory();
        //File new_folder=new File("sdcard0/IntentService_Example");
        //if (!new_folder.exists()){
          //  new_folder.mkdir();
       // }
        File new_file=new File(internal_root,"download_image.jpg");
        try {
            URL url=new URL(path);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();
            int responseCode=connection.getResponseCode();
            if (responseCode!=200)
                throw new Exception("Error in connection");
            InputStream is=connection.getInputStream();
            OutputStream fos=new FileOutputStream(new_file);
           byte[] buffer=new byte[1024];
            int count=0;
            while ((count=is.read(buffer))>0){
                fos.write(buffer,0,count);
            }
            fos.close();
            String file_path=new_file.getPath();
            bundle.putString("file_path",file_path);
            receiver.send(DOWNLOAD_SUCCESS,bundle);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我的错误在哪里?请给我指明正确的方向。

当您将示例结果接收器实例发送到您的服务时 class,您没有发送示例结果接收器的对象 class 实际上您向服务发送了一个空指针 class.

你必须尝试这样做。

public void click(View view){
sampleResultReceiver = new SampleResultReceiver();
        Intent intent=new Intent(MainActivity.this,MyIntentServiceActivity.class);
        intent.putParceleableExtra("receiver",sampleResultReceiver);
        intent.putExtra("url", TextUtils.isEmpty(edt.getText())?defalut_url:edt.getText().toString());
        startService(intent);
        prb.setVisibility(View.VISIBLE);
        prb.setIndeterminate(true);
    }