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

时间:2017-01-06 09:27:10

标签: android android-service android-file android-networking android-intentservice

我正在尝试使用ProgressBar下载图片,但它没有提供图片。只要我保持应用程序但不加载图像,我的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); } } } 就会显示进度。

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

enter image description here

MainActivity:

  

爪哇

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();
        }
    }
}

我的服务类是......

  

爪哇

{{1}}

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

1 个答案:

答案 0 :(得分:0)

当您将Sample Result Receiver实例发送到您的Service类时,您不发送示例结果接收器类的对象infact您向服务类发送空指针。

你必须尝试这样做。

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);
    }