用URL在IntentService中下载图片并更新到ImageView

整个流程还是采用的之前的逻辑,即在Activity触发事件,交给IntentService去处理,并将处理的结果用broadcastReceiver发给Activity内的broadcastReceiver内部类处理,实现对UI的更新,而这个下载图片的过程则是放在了IntentService中进行处理

用URL下载网络上的图片首先要获取网络权限,否则执行到url.openStream()会重启

在AndroidManifest.xml中添加网络权限

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

在Activity中动态注册广播

try
        {
            broadcastReceiver = new ImageReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.example.space.text2.action.IMAGERECEIVER_URLCONNECTION");
            registerReceiver(broadcastReceiver,intentFilter);
            Log.i("mss"," registerReceiver(broadcastReceiver,intentFilter);bbbbbbb");

        }
        catch (ParcelFormatException e)
        {
            Log.i("mss","catch");
        }

通过按钮的点击开启IntentService

       final Button buttondownload = (Button)super.findViewById(R.id.button3);
        final Button buttondisplay = (Button)super.findViewById(R.id.button7);
        buttondownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try
                {
                    Intent  intent = new Intent(TextActivity.this,TextIntentService.class);
                    intent.setAction("com.example.space.text2.action.URLCONNECTION");
                    intent.putExtra("url","http://img-cdn2.luoo.net/pics/vol/5a810230daa52.jpg"); 
                    TextActivity.this.startService(intent);

                }
                catch(ParcelFormatException e)
                {
                    Log.i("mss","catch");
                }
            }
        });

在IntentService的onHandleIntent方法中进行Intent的Action的判断

    @Override
    protected void onHandleIntent(Intent intent) {
        //Log.i("mss","onHandleIntent");
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_MSGFINSIH.equals(action)) {

            }
            else if("com.example.space.text2.action.URLCONNECTION".equals(action))
           {

       }

获取指定Action后进行图片的下载

 else if("com.example.space.text2.action.URLCONNECTION".equals(action))
            {
                //在这里要进行判断,看收到的intent是不是要求进行图片的下载
                URL url=null;


                String urlconnection = intent.getStringExtra("url");

                try{
                    url = new URL(urlconnection);
                }catch(MalformedURLException e)
                {
                    Log.i("mss"," MalformedURLException");
                }


                try{
                    InputStream inputStream = url.openStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                    inputStream = url.openStream();
                    OutputStream outputStream = openFileOutput(urlconnection.split("/")[urlconnection.split("/").length-1],MODE_PRIVATE);
//用urlconnection.split("/")[urlconnection.split("/").length-1],可以获取split后的最后一个元素即图片的名称
                    byte[] bytes = new byte[10240];
                    int hasread =0;
                    while((hasread = inputStream.read(bytes))>0)
                    {
                        outputStream.write(bytes,0,hasread);
                    }
                    inputStream.close();
                    outputStream.close();
                    Intent intent2 = new Intent("com.example.space.text2.action.IMAGERECEIVER_URLCONNECTION");
                    intent2.putExtra("imagename",urlconnection.split("/")[urlconnection.split("/").length-1]);
                    sendBroadcast(intent2);
        //下载完成,发送广播告知Activity可以更新组件了

                }catch(IOException r)
                {

                }


            }

在Activity的broadcastReceiver内部类中获取IntentService返回的结果来更新组件

    public class ImageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO: This method is called when the BroadcastReceiver is receiving
            // an Intent broadcast.
            if (intent != null) {
                final String action = intent.getAction();
                if ("com.example.space.text2.action.IMAGERECEIVER_URLCONNECTION".equals(action)) {
                    String imagename = intent.getStringExtra("imagename");
                    try{
                        FileInputStream fileInputStream = openFileInput(imagename);
                        Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream);
                        imageView.setImageBitmap(bitmap);
                        Toast.makeText(getApplicationContext(), "imageView.setImageBitmap(bitmap)", Toast.LENGTH_SHORT).show();
                    }catch(FileNotFoundException e)
                    {
                        Toast.makeText(getApplicationContext(), "FileNotFoundException "+imagename, Toast.LENGTH_SHORT).show();
                    }

                }
            }
            //
            //Toast.makeText(getApplicationContext(), intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();
//                    TextView textView = (TextView)FinsihActivity.super.findViewById(R.id.textView13);
//                    textView.setText(""+intent.getStringExtra("msg"));


            //throw new UnsupportedOperationException("Not yet implemented");
        }


    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值