android-adapter
TRANSCRIPT
-
7/27/2019 Android-Adapter
1/45
Adapters in Android
-
7/27/2019 Android-Adapter
2/45
Introduction
Adapter is a bridge between Adapter View and its underlying data witview.
Adapters are used to bind data to View Groups that extend the Adaptclass (such as List View or Gallery).
Adapters are responsible for creating child Views that represent the udata within the bound parent View.
can create your own Adapter classes and build your own AdapterView
controls. Android supplies a set of Adapters that can pump data from common
sources (including arrays and Cursors) into the native controls that extAdapter View.
Adapters are responsible both for supplying the data and for creating that represent each item, Adapters can radically modify the appearanfunctionality of the controls theyre bound to.
-
7/27/2019 Android-Adapter
3/45
Native Adapters
ArrayAdapter The Array Adapter uses generics to bind an Adapter View to
of objects of the specified class.
By default, the Array Adapter uses the toString() value of eain the array to create and populate Text Views.
Alternative constructors enable you to use more complex layou can extend the class (as shown in the next section) to bto more complicated layouts.
-
7/27/2019 Android-Adapter
4/45
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 twin thehierarchy
Gallery, a horizontal-scrolling list, principally used for imagthumbnails
These all have a common superclass: AdapterView, so namethey partnerwith objects implementing the Adapter interfacdetermine what choices are available for the user to choose
-
7/27/2019 Android-Adapter
5/45
Using array Adapter
Step1 :Create arrayadapter object Eg String[] items={"this", "is", "a", "really", "silly", "list"};
new ArrayAdapter(this,android.R.layout.simple_list_item_
One flavor of the ArrayAdapter constructor takes three paramete
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 resou
shown above)
3. The actual array or list of items to show
-
7/27/2019 Android-Adapter
6/45
Step2:
Use setAdapter() method to bind the data onto the parent.
Step3:use required listeners to handle the events.
eg;: spinner and listview eg
-
7/27/2019 Android-Adapter
7/45
Customizing Array Adapter
Step1 create your activity (e.g., ListActivity), get your data (e.g., ar
strings), and set up your AdapterView with a simple adaptethe steps outlined in the preceding sections.
Step2 : Design the row
create a layout XML resource that will represent one row inListView (or cell in your GridView or whatever).
? l i "1 0" di " f 8"?
-
7/27/2019 Android-Adapter
8/45
>
/>
>
-
7/27/2019 Android-Adapter
9/45
/>
/>
St 3 E t d th A Ad t
-
7/27/2019 Android-Adapter
10/45
Step3 : Extend the Array Adapter
create our own ListAdapter, by creating our own subclass of Array
Since an Adapter is tightly coupled to the AdapterView that uses isimplest to make the custom ArrayAdapter subclass be an inner c
manages the AdapterView. Step4 : Override constructor and getView() to assign object prope
Views.
The adapter would inflate the layout for each row in its getView()assign the data to the individual views in the row.
The adapter is assigned to the ListViewvia the setAdaptermethod onthe ListViewobject.
Filtering and sorting of the data is handled by the adapter. You
implement the logic in your custom adapter implementation.
-
7/27/2019 Android-Adapter
11/45
publicclass MySimpleArrayAdapter extends ArrayAdapter {
privatefinal Context context;
privatefinal 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]);
-
7/27/2019 Android-Adapter
12/45
String s = values[position];
if(s.startsWith("iPhone")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
}
-
7/27/2019 Android-Adapter
13/45
SimpleCursorAdapter Used to bind the database related data to view.
The SimpleCursorAdapter is used to bind a Cursor to an Adapter View using a
the UI of each row/item. The content of each rows View is populated using the column values of the
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 column
To integer array An array of layout IDs that correspond to the controls in th
The value of the column specified in the from array will be bound to the frommust have the same number of entries because they form a mapping from ththe layout controls in the view.
C t d t d bi d it t th Li t Vi
-
7/27/2019 Android-Adapter
14/45
Create a new adapter and bind it to the List View
vdb = new VegetableDatabase(this);
cursor = vdb.ReadableDatabase.RawQuery("SELECT * FRvegetables", null);
// cursor queryStartManagingCursor(cursor); // use either SimpleCursorAdapter or CursorAdapter subclas// which columns map to which layout controls string[] fromColumns = newstring[] {"name"}; int[] toControlIDs = newint[] {Android.Resource.Id.Text1};// use a SimpleCursorAdapterlistView.Adapter = new
SimpleCursorAdapter (this, Android.Resource.Layout.Simplecursor, fromColumns, toControlIDs);
-
7/27/2019 Android-Adapter
15/45
INTENTS
-
7/27/2019 Android-Adapter
16/45
Introduction Intent: facility for late run-time binding between components in the sa
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 particu
3.Broadcast that an event has occurred
W thi k t I t t bj t t i i b
-
7/27/2019 Android-Adapter
17/45
We can think to an Intent object as a message containing a buinformation.
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. t
It is optional (implicit intent)
void setComponent()
Action name : A string naming the action to be performed.
-
7/27/2019 Android-Adapter
18/45
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
ACTION_ALL_APPS Opens an Activity that lists all the installed applications. Typical
is handled by the launcher.
ACTION_ANSWER Opens an Activity that handles incoming calls. This is normally h
by the native in-call screen.
ACTION_BUG_REPORT Displays an Activity that can report a bug. This is normally
by the native bug-reporting mechanism.
ACTION_CALL Brings up a phone dialer and immediately initiates a call using the nthe 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
ACTION_DIAL.
ACTION_CALL_BUTTON Triggered when the user presses a hardware call button.
typically initiates the dialer Activity.
ACTION DELETE Starts an Activity that lets you delete the data specified at the Intents dat
-
7/27/2019 Android-Adapter
19/45
_ y y p
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 withoutuser 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
-
7/27/2019 Android-Adapter
20/45
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 typeand a subtype
Image/gif image/jpeg image/png image/tifftext/html text/plain text/javascript text/cssvideo/mp4 video/mpeg4 video/quicktime video/ogg
application/vnd.google-earth.kml+xml
Category: A string containing information about the kind of compo
-
7/27/2019 Android-Adapter
21/45
Category: A string containing information about the kind of composhould handle the Intent.
> 1 can be specified for an Intent
void addCategory()
Category: string describing the kind of component that should hanRefer page No: 184
Extra :Additional information that should be delivered to the handparameters).
Key-value pairs
void putExtras() getExtras()
Flags : Additional information that instructs Android how to launchhow to treat it after executed.
Intent Types: Implicit & Explicit Intent
-
7/27/2019 Android-Adapter
22/45
Intent Types: Implicit & Explicit IntentExplicit Intents :
that applications consist of several interrelated screens Activitibe included in the application manifest. To connect them, you ma
explicitly specify which Activity to open. To explicitly select an Activity class to start, create a new Intent sp
current application context and the class of the Activity to launchin to startActivity, as
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);
After calling startActivity, the new Activity (in this example, MyOtbe created and become visible and active, moving to the top of th
Calling finish programmatically on the new Activity will close it anfrom the stack.
Alternatively,users can navigate to the previous Activity using the
button.
Implicit Intents: The target receiver is specified by data type/name
-
7/27/2019 Android-Adapter
23/45
Implicit Intents: The target receiver is specified by data type/name
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,Second
intent.setComponent(component);
startActivity(intent);
Implicit Intents: do not name a target (component name is left blank)
-
7/27/2019 Android-Adapter
24/45
When an Intent is launched, Android checks out which activies could answer to such Inten
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-tim
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://informa
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 actio
When constructing a new implicit Intent to use with startActivity, you nominate an action to
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 dimplicit Intent that requests that the action (dial a number) be performed on aphone numURI), 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 la
Activity fi nishes. To track feedback from the opened form, use the startActivityForResult meth
an Intent is a request for an action to be performed on a set of data.
-
7/27/2019 Android-Adapter
25/45
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 su
How to declare what intents I'm able to handle?
tag in AndroidManifest.xml with the associated attributes action , cate
How?
-
7/27/2019 Android-Adapter
26/45
p
Ie The process of deciding which Activity to start when an implicit Intenstart Activity is called intent resolution.
Android puts together a list of all the Intent Filters available from thepackages.
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 hand
(ACTION Test): The action specified in the Intent must match one of in the filter.
If the filter does not specify any actionFAIL
An intent that does not specify an actionSUCCESS as as long as the filter coaction.
If the intent filter includes the speciied action ->SUCCESS
(Category test) : Intent Filters must include allthe categories defi ned in thel i I b i l d ddi i l i i l d d i h I
-
7/27/2019 Android-Adapter
27/45
resolving Intent, but can include additional categories not included in the Inten
An Intent Filter with no categories specifi ed matches only Intents with no ca
(DATA Test): The URI of the intent is compared with the parts of the URI mfilter (this part might be incompleted).
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 authorityis the section of the URI between the sc
(e.g., developer.android.com). For a hostname to match, the Intent Filters scheme
4. data path is what comes after the authority (e.g., /training). A path can mscheme and hostname parts of the data tag also match.
When you implicitly start an Activity, if more than one component isthis process, all the matching possibilities are offered to the user. For Broadc
matching Receiver will receive the broadcast Intent.
Finding and Using Intents Received Within an Activity :
-
7/27/2019 Android-Adapter
28/45
When an application component is started through an implicit Intent, find the action it is to perform and the data upon which to perform it.
Call the getIntent method usually from within the onCreate methodextract 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
Use the type-safe getExtra methods to extract additional informstored 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 hand
-
7/27/2019 Android-Adapter
29/45
can use the startNextMatchingActivity method to pass responsibility for action handmatching application component
Intent intent = getIntent();
startNextMatchingActivity(intent);
This allows you to add additional conditions to your components that restrict their 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 launspecific Intent by calling resolveActivityon your Intent object, passing in the Package
// 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.resolveAc
if (cn == null) {
// If there is no Activity available to perform the action
} else
startActivity(intent);
}
Returning Results from Activities
-
7/27/2019 Android-Adapter
30/45
Returning Results from ActivitiesActivities 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-Actresults back to its parent.
In addition to passing in the explicit or implicit Intent used to determine which Activity toin a request code. This value will later be used to uniquely identify the subActivity that ha
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 re
When a sub-Activity closes, the onActivityResult event handler is fired within the calling Amethod 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 integewill be either Activity.RESULT_OKor Activity.RESULT_CANCELED.
Data An Intent used to package returned data. It may include a URI that represents a select
The sub-Activity can also return information as an extra within the returned data Intent.
@Override public void onActivityResult(int requestCode
-
7/27/2019 Android-Adapter
31/45
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;
}
}
R i id i k th tR lt()
-
7/27/2019 Android-Adapter
32/45
Receiver side: invoke the setResult()
When your sub-Activity is ready to return, call setResul tbefore finish to retcalling Activity.
The setResultmethod takes two parameters: the result code and the result 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
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 piecas the selected contact, phone number, or media file) and a collection of extrasadditional information.
If the Activity is closed by the user pressing the hardware back key, or finishisprior call to setResult, the result code will be set to RESULT_CANCELED and theto null.
Eg Button okButton = (Button) findViewById(R.id.ok_button);k li k i ( i li k i () {
-
7/27/2019 Android-Adapter
33/45
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();}});
-
7/27/2019 Android-Adapter
34/45
BROADCASTRECEIVERS
Use Intents to Broadcast Events
Use Intents to broadcast messages anonymously between components via thmethod.
-
7/27/2019 Android-Adapter
35/45
Intents are capable of sending structured messages across process boundarieimplement Broadcast Receivers to listen for, and respond to, these Broadcastyour applications.
Broadcast Intents are used to notify applications of system or application eveevent-driven programming model between applications.
Android uses Broadcast Intents extensively to broadcast system events, suchnetwork connectivity, docking state, and incoming calls.
Sender side:
To broadcast event with intents, construct the Intent to broadcast and call sesend it.
Set the action, data, and category of your Intent in a way that lets Broadcast accurately determine their interest.
the Intent action string is used to identify the event being broadcast, so it shstring that identifi es the event. By convention, action strings are constructedform as Java package names:
public static final String NEW_LIFEFORM_DETECTED =com.paad.action.NEW_
to include data within the Intent, specify a URI using the Intents data proper
can also include extras to add additional primitive values.
Intent intent = new Intent(LifeformDetectedReceiver.NEW_LIFEFORM); intent putExtra(LifeformDetectedReceiver EXTRA LIFEFORM NAME
-
7/27/2019 Android-Adapter
36/45
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 Intent
For a Receiver to receive broadcasts, it must be registered, either in coapplication manifest the latter case is referred to as a manifest Rece
In either case, use an Intent Filter to specify which Intent actions and dReceiver is listening for.
In the case of applications that include manifest Receivers, the applications dont have to beIntent is broadcast for those receivers to execute; they will be started automatically when a
-
7/27/2019 Android-Adapter
37/45
broadcast.
This is excellent for resource management, as it lets create event-driven applications that wbroadcast 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 hand
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 Inmatches the Intent Filter used to register the Receiver.
The onReceive handler must complete within fi ve seconds; otherwise, the Force Close dial
Typically, Broadcast Receivers will update content, launch Services, update Activity UI, or noNotifi cation Manager. The fi ve-second execution limit ensures that major processing cannodone within the Broadcast Receiver itself.
Step2: register BroadcastReceivers
Receiver registered programmatically will respond to Broadcast Intents only w
-
7/27/2019 Android-Adapter
38/45
g p g y p yapplication component it is registered within is running.
register the Receiver within the onResume handler and unregister it during
Eg private IntentFilter filter =new IntentFilter(LifeformDetectedReceiver.NE
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 applicareceiver tag within the application node, specifying the class name of the Broadcast Receive
-
7/27/2019 Android-Adapter
39/45
The receiver node needs to include an intent-filter tag that specifi es the action string being
Broadcast Receivers registered this way are always active and will receive Broadcast Intents application has been killed or hasnt been started.
Broadcasting Ordered Intents
When the order in which the Broadcast Receivers receive the Intent is important particulallow Receivers to affect the Broadcast Intent received by future Receivers use sendOrder
String requiredPermission = com.paad.MY_BROADCAST_PERMISSION;
sendOrderedBroadcast(intent, requiredPermission);
Using this method, Intent will be delivered to all registered Receivers that hold the requiredspecifi ed) in the order of their specifi ed priority.
specify the priority of a Broadcast Receiver using the android:priority attribute within its Intnode where hi her values are considered hi her riorit .
-
7/27/2019 Android-Adapter
40/45
android:name= .MyOrderedReceiver
android:permission=com.paad.MY_BROADCAST_PERMISSION>
Local Broadcast Manager
Local Broadcast Manager simplify the process of registering for, and se
Intents between components within application. It ensures that the Intent that broadcast cannot be received by any co
outside application, ensuring that there is no risk of leaking private or ssuch as location information.
Similarly, other applications cant transmit broadcasts to your Receiverrisk of these Receivers becoming vectors for security exploits.
Use the LocalBroadcastManager.getInstance method to return an instaBroadcast Manager:
-
7/27/2019 Android-Adapter
41/45
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(th
Receiver side:To register a local broadcast Receiver, use the Local BroadregisterReceiver method, much as you would register a global receiver,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 Int
Sender side: To transmit a local Broadcast Intent, use the Local BroadcsendBroadcast method, passing in the Intent to broadcast:
lbm.sendBroadcast(new Intent(LOCAL_ACTION));
The Local Broadcast Manager also includes a sendBroadcastSync methsynchronously, blocking until each registered Receiver has been dispatc
-
7/27/2019 Android-Adapter
42/45
INTERNET
Android includes several classes to handle network communications. They arjava.net.* and android.net.* packages.
T I t t dd INTERNET i i d t
-
7/27/2019 Android-Adapter
43/45
To access Internet resources, add an INTERNET uses-permission node to appas
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 lo
-
7/27/2019 Android-Adapter
44/45
The Download Manager is a Service to optimize the handling of lodownloads.
The Download Manager handles the HTTP connection and monitochanges and system reboots to ensure each download completes
To access the Download Manager, request the DOWNLOAD_SERVgetSystemService method
String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager = (DownloadManager)getSystemService(serviceUri uri = Uri.parse(http://developer.android.com/shareables/icon_v4.0.zip);
DownloadManager.Request request = new Request(uri);
long reference = downloadManager.enqueue(request);
use the returned reference value to perform future actions or quedownload,including checking its status or canceling it.
-
7/27/2019 Android-Adapter
45/45
, g g g
can add an HTTP header to your request, or override the mime tythe server, by calling addRequestHeader and setMimeType, respeRequest object.
After calling enqueue, the download begins as soon as connectivitand the Download Manager is free.