Download pictures in IntentService with URL and update them to ImageView

Keywords: network Android xml

The whole process still adopts the previous logic, that is, when an Activity triggers an event, it is handed over to the IntentService for processing, and the processed result is sent to the internal class of the broadcastReceiver in the Activity for processing, so as to update the UI. The process of downloading the picture is put into the IntentService for processing

To download a picture on the network with a URL, you need to obtain the network permission first, otherwise executing to url.openStream() will restart

Add network permissions in Android manifest.xml

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

Dynamically register broadcast in 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");
        }

Open the IntentService by clicking the button

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

Judge the Action of Intent in the onHandleIntent method of IntentService

    @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))
           {

       }

Download the picture after obtaining the specified Action

 else if("com.example.space.text2.action.URLCONNECTION".equals(action))
            {
                //Here we need to judge whether the received intent requires downloading the pictures
                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);
//With urlconnection.split("/")[urlconnection.split("/").length-1], you can get the name of the last element after split, that is, the picture
                    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);
        //Download completed, send broadcast to inform Activity that the component can be updated

                }catch(IOException r)
                {

                }


            }

Get the result returned by the IntentService in the Activity's broadcastReceiver inner class to update the component

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


    }

Posted by evil turnip on Sun, 05 Apr 2020 12:40:03 -0700