Vous êtes sur la page 1sur 45

Adapters in Android

Introduction
Adapter is a bridge between Adapter View and its underlying data within that view. Adapters are used to bind data to View Groups that extend the AdapterView class (such as List View or Gallery). Adapters are responsible for creating child Views that represent the underlying data within the bound parent View. can create your own Adapter classes and build your own AdapterView-derived controls. Android supplies a set of Adapters that can pump data from common data sources (including arrays and Cursors) into the native controls that extend Adapter View. Adapters are responsible both for supplying the data and for creating the Views that represent each item, Adapters can radically modify the appearance and functionality of the controls theyre bound to.

Native Adapters
ArrayAdapter The Array Adapter uses generics to bind an Adapter View to an array of objects of the specified class. By default, the Array Adapter uses the toString() value of each object in the array to create and populate Text Views. Alternative constructors enable you to use more complex layouts, or you can extend the class (as shown in the next section) to bind data to more complicated layouts.

Adapter Based Controls


ListView, which is your typical list box Spinner, which (more or less) is a drop-down list GridView, offering a two-dimensional roster of choices ExpandableListView, a limited tree widget, supporting two levels in thehierarchy Gallery, a horizontal-scrolling list, principally used for image thumbnails These all have a common superclass: AdapterView, so named because they partnerwith objects implementing the Adapter interface to determine what choices are available for the user to choose from.

Using array Adapter


Step1 :Create arrayadapter object Eg String[] items={"this", "is", "a", "really", "silly", "list"}; new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items); One flavor of the ArrayAdapter constructor takes three parameters: 1. The Context to use (typically this will be your activity instance) 2. The resource ID of a view to use (such as a built-in system resource ID, as shown above) 3. The actual array or list of items to show

Step2: Use setAdapter() method to bind the data onto the parent. Step3:use required listeners to handle the events. eg;: spinner and listview eg

Customizing Array Adapter


Step1 create your activity (e.g., ListActivity), get your data (e.g., array of Java strings), and set up your AdapterView with a simple adapter following the steps outlined in the preceding sections. Step2 : Design the row create a layout XML resource that will represent one row in your ListView (or cell in your GridView or whatever).

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal">> <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"

android:layout_gravity="center_vertical"
android:padding="2dip" android:src="@drawable/ok" android:contentDescription="@string/icon"/>/> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"

android:orientation="vertical">>

<TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp" android:textStyle="bold"/>/> <TextView android:id="@+id/size"android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp"/>/> </LinearLayout> </LinearLayout>

Step3 : Extend the Array Adapter create our own ListAdapter, by creating our own subclass of ArrayAdapter. Since an Adapter is tightly coupled to the AdapterView that uses it, it is typically simplest to make the custom ArrayAdapter subclass be an inner class of whoever manages the AdapterView. Step4 : Override constructor and getView() to assign object properties to layout Views. The adapter would inflate the layout for each row in its getView() method and assign the data to the individual views in the row. The adapter is assigned to the ListView via the setAdapter method on the ListView object. Filtering and sorting of the data is handled by the adapter. You need to implement the logic in your custom adapter implementation.

public class MySimpleArrayAdapter extends ArrayAdapter<String> { private final Context context; private final String[] values; public MySimpleArrayAdapter(Context context, String[] values) { super(context, R.layout.rowlayout, values); this.context = context;

this.values = values;

@Override

public View getView(int position, View convertView, ViewGroup parent) {


LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.rowlayout, parent, false); TextView textView = (TextView) rowView.findViewById(R.id.label); ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); textView.setText(values[position]);

String s = values[position]; if (s.startsWith("iPhone")) { imageView.setImageResource(R.drawable.no); } else { imageView.setImageResource(R.drawable.ok); } return rowView; } }

SimpleCursorAdapter
Used to bind the database related data to view. The SimpleCursorAdapter is used to bind a Cursor to an Adapter View using a layout to define the UI of each row/item. The content of each rows View is populated using the column values of the corresponding row in the underlying Cursor. The parameters for the SimpleCursorAdapter constructor are: Context A reference to the containing Activity. Layout The resource ID of the row view to use. ICursor A cursor containing the SQLite query for the data to display. From string array An array of strings corresponding to the names of columns in the cursor. To integer array An array of layout IDs that correspond to the controls in the row layout. The value of the column specified in the from array will be bound to the from and to arrays must have the same number of entries because they form a mapping from the data source to the layout controls in the view.

Create a new adapter and bind it to the List View vdb = new VegetableDatabase(this); cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM vegetables", null); // cursor query StartManagingCursor(cursor); // use either SimpleCursorAdapter or CursorAdapter subclass here! // which columns map to which layout controls string[] fromColumns = new string[] {"name"}; int[] toControlIDs = new int[] {Android.Resource.Id.Text1}; // use a SimpleCursorAdapter listView.Adapter = new SimpleCursorAdapter (this, Android.Resource.Layout.SimpleListItem1, cursor, fromColumns, toControlIDs);

INTENTS

Introduction
Intent: facility for late run-time binding between components in the same or different applications. Call a component from another component Possible to pass data between components Something like:

Android, please do that with this data

Reuse already installed applications Components: Activities, Services, Broadcast receivers Use intents for the following 1.Explicitly start a particular Service or Activity using its class name 2. Start an Activity or Service to perform an action with (or on) a particular piece of data 3.Broadcast that an event has occurred

We can think to an Intent object as a message containing a bundle of information.


Information of interests for the receiver (e.g. data) Information of interests for the Android system (e.g. category).

Structure of an Intent -> Component name ->Action ->Category ->Data ->Extra info ->Flags Component Name :Component that should handle the intent (i.e. the receiver). It is optional (implicit intent) void setComponent()

Action name : A string naming the action to be performed. Pre-defined, or can be specified by the programmer. void setAction() Predefined actions (http://developer.android.com/reference/android/content/Intent.html) ACTION_ALL_APPS Opens an Activity that lists all the installed applications. Typically, this

is handled by the launcher.


ACTION_ANSWER Opens an Activity that handles incoming calls. This is normally handled by the native in-call screen.

ACTION_BUG_REPORT Displays an Activity that can report a bug. This is normally handled
by the native bug-reporting mechanism. ACTION_CALL Brings up a phone dialer and immediately initiates a call using the number supplied in the Intents data URI. This action should be used only for Activities that

replace the native dialer application. In most situations it is considered better form to use
ACTION_DIAL. ACTION_CALL_BUTTON Triggered when the user presses a hardware call button. This

typically initiates the dialer Activity.

ACTION_DELETE Starts an Activity that lets you delete the data specified at the Intents data URI. ACTION_DIAL Brings up a dialer application with the number to dial prepopulated from the Intents data URI. By default, this is handled by the native Android phone dialer. The dialer can normalize most number schemas for example, tel:555-1234and tel:(212) 555 1212are both valid numbers. ACTION_EDIT Requests an Activity that can edit the data at the Intents data URI. ACTION_INSERT Opens an Activity capable of inserting new items into the Cursor specified in the Intents data URI. When called as a sub-Activity, it should return a URI to the newly

inserted item.
ACTION_PICK Launches a sub-Activity that lets you pick an item from the Content Provider specified by the Intents data URI. When closed, it should return a URI to the item that was picked. The Activity launched depends on the data being picked for example, passingcontent://contacts/peoplewill invoke the native contacts list. ACTION_SEARCH Typically used to launch a specific search Activity. When its fired without a specific Activity, the user will be prompted to select from all applications that support search. Supply the search term as a string in the Intents extras using SearchManager.QUERY

Defined by the programmer

it.example.projectpackage.FILL_DATA (package prefix + name action)

Data : Data passed from the caller to the called Component. Location of the data (URI) and Type of the data (MIME type) void setData() Each data is specified by a name and/or type. name: Uniform Resource Identifier (URI) scheme://host:port/path content://com.example.project:200/folder content://contacts/people content://contacts/people/1 Each data is specified by a name and/or type.

type: MIME (Multipurpose Internet Mail Extensions)-type Composed by two parts: a type and a subtype
Image/gif image/jpeg image/png image/tiff text/html text/plain text/javascript text/css video/mp4 video/mpeg4 video/quicktime video/ogg application/vnd.google-earth.kml+xml

Category: A string containing information about the kind of component that should handle the Intent. > 1 can be specified for an Intent void addCategory() Category: string describing the kind of component that should handle the intent. Refer page No: 184 Extra :Additional information that should be delivered to the handler(e.g. parameters). Key-value pairs void putExtras() getExtras() Flags : Additional information that instructs Android how to launch an activity, and how to treat it after executed.

Intent Types: Implicit & Explicit Intent


Explicit Intents : that applications consist of several interrelated screens Activities that must be included in the application manifest. To connect them, you may want to explicitly specify which Activity to open. To explicitly select an Activity class to start, create a new Intent specifying the current application context and the class of the Activity to launch. Pass this Intent in to startActivity, as Intent intent = new Intent(MyActivity.this, MyOtherActivity.class); startActivity(intent); After calling startActivity, the new Activity (in this example, MyOtherActivity) will be created and become visible and active, moving to the top of the Activity stack. Calling finish programmatically on the new Activity will close it and remove it from the stack. Alternatively,users can navigate to the previous Activity using the devices Back button.

Implicit Intents: The target receiver is specified by data type/names. The system chooses the receiver that matches the request. Explicit Intents : The target receiver is specified through the Component Name Specify the activity that will handle the intent. Intent intent=new Intent(this, SecondActivity.class); startActivity(intent); OR Intent intent=new Intent(); ComponentName component=new ComponentName(this,SecondActivity.class); intent.setComponent(component); startActivity(intent);

Implicit Intents: do not name a target (component name is left blank) When an Intent is launched, Android checks out which activies could answer to such Intent If at least one is found, then that activity is started! Binding does not occur at compile time, nor at install time, but at run-time (late run-time binding) Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://informatica.unibo.it")); startActivity(i);

Implicit intents are very useful to re-use code and to launch external applications More than a Component can match the Intent request Implicit Intents are a mechanism that lets anonymous application components service action requests. When constructing a new implicit Intent to use with startActivity, you nominate an action to perform and, optionally, supply the data on which to perform that action. Eg if you want to let users make calls from an application, rather than implementing a new dialer you could use an implicit Intent that requests that the action (dial a number) be performed on aphone number (represented as a URI), as shown in the code snippet below: Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse(tel:555-2368)); startActivity(intent); When using startActivity, your application wont receive any notifi cation when the newly launched

Activity fi nishes. To track feedback from the opened form, use the startActivityForResult method

an Intent is a request for an action to be performed on a set of data. how does Android know which application (and component) to use to service that request? Using Intent Filters, application components can declare the actions and data they support.

How to declare what intents I'm able to handle? <intent-filter> tag in AndroidManifest.xml with the associated attributes action , category, data. How? <intent-filter> <action android:name=my.project.ACTION_ECHO /> <category android:name=android.intent.category.DEFAULT/> <category android:name=android.intent.category.SELECTED_ALTERNATIVE/>

<data android:mimeType=vnd.earthquake.cursor.item/*/> </intent-filter>

If anyone calls an Intent with my.project.ACTION_ECHO as action, our activity will be called

When constructing a new implicit Intent, you specify an action to perform and, optionally, supply the URI of the data on which to perform that action. You can send additional data to the target Activity by adding extras to the Intent.

The intent resolution process resolves the Intent-Filter that can handle a given Intent. Ie The process of deciding which Activity to start when an implicit Intent is passed in to start Activity is called intent resolution. Android puts together a list of all the Intent Filters available from the installed packages. Three tests to be passed:
Action field test Category field test Data field test

If the Intent-filter passes all the three test, then it is selected to handle the Intent. (ACTION Test): The action specified in the Intent must match one of the actions listed in the filter.
If the filter does not specify any action FAIL An intent that does not specify an action SUCCESS as as long as the filter contains at least one action. If the intent filter includes the speciied action ->SUCCESS

(Category test) : Intent Filters must include all the categories defi ned in the resolving Intent, but can include additional categories not included in the Intent. An Intent Filter with no categories specifi ed matches only Intents with no categories. (DATA Test): The URI of the intent is compared with the parts of the URI mentioned in the filter (this part might be incompleted). <intent-filer > <data android:mimeType=audio/* android:scheme=http/> <data android:mimeType=video/mpeg android:scheme=http/> </intent-filter> Both URI and MIME-types are compared (4 different sub-cases ) 1.The MIME type is the data type of the data being matched. 2.The scheme is the protocol part of the URI (e.g., http:, mailto:, or tel:). 3.The hostname or data authority is the section of the URI between the scheme and the path (e.g., developer.android.com). For a hostname to match, the Intent Filters scheme must also pass. 4. data path is what comes after the authority (e.g., /training). A path can match only if the scheme and hostname parts of the data tag also match.

When you implicitly start an Activity, if more than one component is resolved from this process, all the matching possibilities are offered to the user. For Broadcast Receivers, each
matching Receiver will receive the broadcast Intent.

Finding and Using Intents Received Within an Activity : When an application component is started through an implicit Intent, it needs to find the action it is to perform and the data upon which to perform it. Call the getIntent method usually from within the onCreate method to extract the Intent used to launch a component, as shown below: public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Intent intent = getIntent(); } Use the getData and getAction methods to find the data and action of the Intent. Use the type-safe get<type>Extra methods to extract additional information stored in its extras Bundle. String action = intent.getAction(); Uri data = intent.getData();

Passing on Responsibility: can use the startNextMatchingActivity method to pass responsibility for action handling to the next best matching application component Intent intent = getIntent(); startNextMatchingActivity(intent); This allows you to add additional conditions to your components that restrict their use beyond the ability of the Intent Filterbased Intent resolution process. Determining If an Intent Will Resolve its good practice to determine if your call will resolve to an Activity startActivity. You can query the Package Manager to determine which, if any, Activity will be launched to service a specific Intent by calling resolveActivityon your Intent object, passing in the Package Manager // Create the impliciy Intent to use to start a new Activity. Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(tel:555-2368)); // Check if an Activity exists to perform this action. PackageManager pm = getPackageManager(); ComponentName cn = intent.resolveActivity(pm); if (cn == null) { // If there is no Activity available to perform the action } else startActivity(intent); }

Returning Results from Activities Activities could return results ....Useful for calling activities and have some data back
Sender side:step1: invoke the startActivityForResult() for starting an Activity as a sub-Activity that can pass results back to its parent. In addition to passing in the explicit or implicit Intent used to determine which Activity to launch, you also pass in a request code. This value will later be used to uniquely identify the subActivity that has returned a result. startActivityForResult(Intent intent, int requestCode); Eg Intent intent = new Intent(this, MyOtherActivity.class); startActivityForResult(intent, SHOW_SUBACTIVITY); Step2: handling subactivity results by overriding onActivityResult(int requestCode, int resultCode, Intent data) When a sub-Activity closes, the onActivityResult event handler is fired within the calling Activity. Override this method to handle the results returned. Request code The request code that was used to launch the returning sub-Activity.

Result code The result code set by the sub-Activity to indicate its result. It can be any integer value, but typically will be either Activity.RESULT_OKor Activity.RESULT_CANCELED. Data An Intent used to package returned data. It may include a URI that represents a selected piece of content. The sub-Activity can also return information as an extra within the returned data Intent.

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case (SELECT_HORSE): if (resultCode == Activity.RESULT_OK) selectedHorse = data.getData(); break; case (SELECT_GUN): if (resultCode == Activity.RESULT_OK) selectedGun = data.getData(); break; default: break; } }

Receiver side: invoke the setResult() When your sub-Activity is ready to return, call setResul tbefore finish to return a result to the calling Activity. The setResultmethod takes two parameters: the result code and the result data itself, represented as an Intent. void setResult(int resultCode, Intent data)
void setResult(int resultCode, Intent data); finish(); The result is delivered to the caller component only after invoking the finish() method! The result code is the result of running the sub-Activity generally, either Activity.RESULT_OK or Activity.RESULT_CANCELED. The Intent returned as a result often includes a data URI that points to a piece of content (such as the selected contact, phone number, or media file) and a collection of extras used to return additional information. If the Activity is closed by the user pressing the hardware back key, or finishis called without a prior call to setResult, the result code will be set to RESULT_CANCELED and the result Intent set to null.

Eg Button okButton = (Button) findViewById(R.id.ok_button); okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { long selected_horse_id = listView.getSelectedItemId(); Uri selectedHorse = Uri.parse(content://horses/ + selected_horse_id); Intent result = new Intent(Intent.ACTION_PICK, selectedHorse); setResult(RESULT_OK, result); finish();}}); Button cancelButton = (Button) findViewById(R.id.cancel_button); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); finish();}});

BROADCAST RECEIVERS
Use Intents to Broadcast Events

Use Intents to broadcast messages anonymously between components via the sendBroadcast method. Intents are capable of sending structured messages across process boundaries so we can implement Broadcast Receivers to listen for, and respond to, these Broadcast Intents within your applications. Broadcast Intents are used to notify applications of system or application events, extending the event-driven programming model between applications. Android uses Broadcast Intents extensively to broadcast system events, such as changes in network connectivity, docking state, and incoming calls. Sender side: To broadcast event with intents, construct the Intent to broadcast and call sendBroadcast to send it. Set the action, data, and category of your Intent in a way that lets Broadcast Receivers accurately determine their interest. the Intent action string is used to identify the event being broadcast, so it should be a unique string that identifi es the event. By convention, action strings are constructed using the same form as Java package names: public static final String NEW_LIFEFORM_DETECTED =com.paad.action.NEW_LIFEFORM; to include data within the Intent, specify a URI using the Intents data property. can also include extras to add additional primitive values.

Intent intent = new Intent(LifeformDetectedReceiver.NEW_LIFEFORM); intent.putExtra(LifeformDetectedReceiver.EXTRA_LIFEFORM_NAME, detectedLifeform); intent.putExtra(LifeformDetectedReceiver.EXTRA_LONGITUDE, currentLongitude); intent.putExtra(LifeformDetectedReceiver.EXTRA_LATITUDE, currentLatitude); sendBroadcast(intent);

Receiver side: Broadcast Receivers or Receivers are used to listen for Broadcast Intents. For a Receiver to receive broadcasts, it must be registered, either in code or within the application manifest the latter case is referred to as a manifest Receiver. In either case, use an Intent Filter to specify which Intent actions and data your Receiver is listening for.

In the case of applications that include manifest Receivers, the applications dont have to be running when the Intent is broadcast for those receivers to execute; they will be started automatically when a matching Intent is broadcast. This is excellent for resource management, as it lets create event-driven applications that will still respond to broadcast events even after theyve been closed or killed. To create a new Broadcast Receiver, Step1: create a class that extend BroadcastReceiver and override the onReceive event handler: public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {

//TODO: React to the Intent received.


}} The onReceive method will be executed on the main application thread when a Broadcast Intent is received that matches the Intent Filter used to register the Receiver.

The onReceive handler must complete within fi ve seconds; otherwise, the Force Close dialog will be displayed.
Typically, Broadcast Receivers will update content, launch Services, update Activity UI, or notify the user using the Notifi cation Manager. The fi ve-second execution limit ensures that major processing cannot, and should not, be done within the Broadcast Receiver itself.

Step2: register BroadcastReceivers Receiver registered programmatically will respond to Broadcast Intents only when the application component it is registered within is running. register the Receiver within the onResume handler and unregister it during onPause. Eg private IntentFilter filter =new IntentFilter(LifeformDetectedReceiver.NEW_LIFEFORM); private LifeformDetectedReceiver receiver =new LifeformDetectedReceiver(); @Override public void onResume() { super.onResume(); // Register the broadcast receiver registerReceiver(receiver, filter); } @Override public void onPause() { // Unregister the receiver unregisterReceiver(receiver); super.onPause(); }

To Register Receiver in the application manifest, include a Broadcast Receiver in the application manifest, add a receiver tag within the application node, specifying the class name of the Broadcast Receiver to register.

The receiver node needs to include an intent-filter tag that specifi es the action string being listened for.
<receiver android:name=.LifeformDetectedReceiver > <intent-filter> <action android:name=com.paad.alien.action.NEW_LIFEFORM/> </intent-filter> </receiver> Broadcast Receivers registered this way are always active and will receive Broadcast Intents even when the application has been killed or hasnt been started. Broadcasting Ordered Intents When the order in which the Broadcast Receivers receive the Intent is important particularly where you want to allow Receivers to affect the Broadcast Intent received by future Receivers use sendOrderedBroadcast String requiredPermission = com.paad.MY_BROADCAST_PERMISSION; sendOrderedBroadcast(intent, requiredPermission); Using this method, Intent will be delivered to all registered Receivers that hold the required permission (if one is specifi ed) in the order of their specifi ed priority. specify the priority of a Broadcast Receiver using the android:priority attribute within its Intent Filter manifest node,where higher values are considered higher priority.

<receiver android:name=.MyOrderedReceiver android:permission=com.paad.MY_BROADCAST_PERMISSION> <intent-filter android:priority=100> <action android:name=com.paad.action.ORDERED_BROADCAST /> </intent-filter> </receiver> Local Broadcast Manager Local Broadcast Manager simplify the process of registering for, and sending, Broadcast Intents between components within application. It ensures that the Intent that broadcast cannot be received by any components outside application, ensuring that there is no risk of leaking private or sensitive data, such as location information. Similarly, other applications cant transmit broadcasts to your Receivers, negating the risk of these Receivers becoming vectors for security exploits.

Use the LocalBroadcastManager.getInstance method to return an instance of the Local Broadcast Manager: LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); Receiver side:To register a local broadcast Receiver, use the Local Broadcast Managers registerReceiver method, much as you would register a global receiver, passing in a Broadcast Receiver and an Intent Filter: lbm.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Handle the received local broadcast }}, new IntentFilter(LOCAL_ACTION)); the Broadcast Receiver specifi ed can also be used to handle global Intent broadcasts. Sender side: To transmit a local Broadcast Intent, use the Local Broadcast Managers sendBroadcast method, passing in the Intent to broadcast: lbm.sendBroadcast(new Intent(LOCAL_ACTION)); The Local Broadcast Manager also includes a sendBroadcastSync method that operates synchronously, blocking until each registered Receiver has been dispatched.

INTERNET

Android includes several classes to handle network communications. They are available in the java.net.* and android.net.* packages. To access Internet resources, add an INTERNET uses-permission node to application manifest, as <uses-permission android:name=android.permission.INTERNET/> Eg for opening an internet data stream String myFeed = getString(R.string.my_feed); try { URL url = new URL(myFeed); // Create a new HTTP URL connection URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); processStream(in); }} catch (MalformedURLException e) { Log.d(TAG, Malformed URL Exception}

USING THE DOWNLOAD MANAGER The Download Manager is a Service to optimize the handling of long-running downloads. The Download Manager handles the HTTP connection and monitors connectivity changes and system reboots to ensure each download completes successfully. To access the Download Manager, request the DOWNLOAD_SERVICE using the getSystemService method String serviceString = Context.DOWNLOAD_SERVICE; DownloadManager downloadManager; downloadManager = (DownloadManager)getSystemService(serviceString); Uri uri = Uri.parse(http://developer.android.com/shareables/icon_templatesv4.0.zip); DownloadManager.Request request = new Request(uri); long reference = downloadManager.enqueue(request);

use the returned reference value to perform future actions or queries on the download,including checking its status or canceling it. can add an HTTP header to your request, or override the mime type returned by the server, by calling addRequestHeader and setMimeType, respectively, on Request object. After calling enqueue, the download begins as soon as connectivity is available and the Download Manager is free.

Vous aimerez peut-être aussi