15.03.2017 Views

0321956567

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Anyone listening for the broadcast intent com.peachpit.TRANSACTION_DONE will be notified<br />

that an image download has finished. They will be able to pull both the URL (so they can<br />

tell if it was an image it actually requested) and the location of the cached file.<br />

Rendering the download<br />

In order to interact with the downloading service, there are two steps you’ll need to take.<br />

You’ll need to start the service (with the URL you want it to fetch). Before it starts, however,<br />

you’ll need to register a listener for the result broadcast. You can see these two steps in the<br />

following code:<br />

public void onCreate(Bundle extras){<br />

super.onCreate(extras);<br />

setContentView(R.layout.image_layout);<br />

IntentFilter intentFilter = new IntentFilter();<br />

intentFilter.addAction(ImageIntentService.TRANSACTION_DONE);<br />

registerReceiver(imageReceiver, intentFilter);<br />

Intent i = new Intent(this, ImageIntentService.class);<br />

i.putExtra(“url”, getIntent().getExtras().getString(“url”));<br />

startService(i);<br />

}<br />

pd = ProgressDialog.show(this,<br />

“Fetching Image”,<br />

“Go intent service go!”);<br />

This code registered a receiver (so you can take action once the download is finished),<br />

started the service, and, finally, showed a loading dialog box to the user.<br />

Now take a look at what the imageReceiver class looks like:<br />

private BroadcastReceiver imageReceiver = new BroadcastReceiver() {<br />

@Override<br />

public void onReceive(Context context, Intent intent) {<br />

String location = intent.getExtras().getString(“location”);<br />

if(TextUtils.isEmpty(location){<br />

String failedString = “Failed to download image”;<br />

Toast.makeText(context, failedString , Toast.LENGTH_LONG).show();<br />

}<br />

File imageFile = new File(location);<br />

if(!imageFile.exists()){<br />

pd.dismiss();<br />

98 Chapter 4 Acquiring Data

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!