Using Intents in Android
This tutorials describes the usage of intents to communicate between Android components. It is based on Eclipse 4.3, Java 1.6 and Android 4.3.
Table of Contents
Intents are asynchronous messages which allow application components to request functionality from other Android components. Intents allow you to interact with components from the own and other applications. For example an activity can start an external activity for taking a picture.
Intents are objects of the
android.content.Intent
type. Your code can send them to the Android system defining the components you are targeting. For example via the startActivity()
method you can define that the intent should be used to start an activity.An intent can contain data via a
Bundle
. This data can be used by the receiving component.To start an activity use the method
startActivity(intent)
. This method is defined on theContext
object which Activity
extends.The following code demonstrates how you can start another activity via an intent.
# Start the activity connect to the
# specified class
Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);
Activities which are started by other Android activities are called sub-activities. This wording makes it easier to describe which activity is meant.
You can also start service via intents. Use the
startService(Intent)
method call for that.Intents are used to signal to the Android system that a certain event has occurred. Intents often describes the action which should be performed and provide data on which such an action should be done. For example your application can start via an intent a browser component for a certain URL. This is demonstrated by the following example.
String url = "http://www.vogella.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
But how does the Android system identify the components which can react to a certain intent?
For this the concept of an intent filter is used. An intent filter specifies the types of intents to which that an activity , service, or broadcast receiver can respond to. It declares therefore the capabilities of a component.
Android components register intent filters either staticially in the
AndroidManifest.xml
or in case of a broadcast receiver also dynamically via code. An intent filter is defined by its category, action and data filters. It can also contain additional metadata.If an intent is send to the Android system, the Android platform runs, using the data included in the
Intent
object, an receiver determination. In this it determines the components which are registered for the data of the intent. If several components have registered for the same intent filter the user can decide which component should be started.Android supports explicit and implicit Intents.
An application can define the target component directly in the intent (explicit intent) or ask the Android system to evaluate registered components based on the intent data (implicit intents).
Explicit intents explicitly defines the component which should be called by the Android system, by using the Java class as identifier.
The following shows how to create an explicit intents and send it to the Android system. If that class represents an activity
Intent
the Android system start it.Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
s Explicit intents are typically used within on application as the classes in an application are controlled by the application developer.
Implicit intents specify the action which should be performed and optionally data which provides data for the action.
For example the following tells the Android system to view a webpage. All installed web browsers should be registered to the corresponding intent data via an intent filter.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com"));
startActivity(i);
If an explicit intent is send to the Android system, it searches for all components which are registered for the specific action and the fitting data type.
If only one component is found, Android starts this component directly. If several components are identifier by the Android system, the user will get an selection dialog and can decide which component should be used for the intent.
An intent contains the action and optionally additional data. The component which creates the
Intent
can add data to it via the overloaded putExtra()
method. Extras are key/value pairs; the key is always a String. As value you can use the primitive data types (int, float,..) plus objects of type String, Bundle, Parceable and Serializable.The receiving component can access this information via the
getAction()
and getData()
methods on the Intent
object. This Intent
object can be retrieved via the getIntent()
method.The component which receives the intent can use the
getIntent().getExtras()
method call to get the extra data.Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
// do something with the data
}
Lots of Android applications allow you to share some data with other people, e.g. the Facebook, G+, Gmail and Twitter application. You can send data to one of this components. The following code snippet demonstrates that.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);
An activity can be closed via the back button on the phone. In this case the
finish()
method is performed. If the activity was started with the startActivity(Intent)
method call, the caller requires no result or feedback from the activity which now is closed.If you start the activity with the
startActivityForResult()
method call, you expect feedback from the sub-activity. Once the sub-activity ends the onActivityResult()
method on the sub-activity is called and you can perform actions based on the result.In the
startActivityForResult()
method call you can specify a result code to determine which activity you started. This result code is returned to you. The started activity can also set a result code which the caller can use to determine if the activity was canceled or not.The sub-activity uses the
finish()
method to create a new intent and to put data into it. It also set an result via the setResult()
method call.The following example code demonstrates how to trigger and intent with the
startActivityForResult()
method.public void onClick(View view) {
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
// Set the request code to any code you like, you can identify the
// callback via this code
startActivityForResult(i, REQUEST_CODE);
}
If you use the
startActivityForResult()
method then the started activity is called a Sub-Activity
.If the sub-activity is finished it can send data back to its caller via Intent. This is done in the
finish()
method.@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
// Activity finished ok, return the data
setResult(RESULT_OK, data);
super.finish();
}
Once the sub-activity finishes, the
onActivityResult()
method in the calling activity is be called.@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this, data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
}
}
You can register your own components via intent filters. If a component does not define one, it can only be called by explicit intent. This chapter gives some example for registering a component for an intent. The key for this registration is that your component registers for the correct action, mime-type and specifies the correct meta-data.
The following code will register an Activity for the Intent which is triggered when someone wants to open a webpage.
<activity android:name=".BrowserActivitiy"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http"/>
</intent-filter>
</activity>
The following example registers an activity for the
ACTION_SEND
intent. It declares itself only relevant for the text/plain
mime type.<activity
android:name=".ActivityTest"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
If a component does not define an Intent filter, it can only be called by explicit Intents.
Intents can also be used to send broadcast messages into the Android system.
BroadcastReceivers
can register to event and will get notified if such an event is triggered.Your application can register to system events, e.g. a new email has arrived, system boot is complete or a phone call is received and react accordingly.
As said earlier, since Android version 3.1 the Android system will per default exclude all
BroadcastReceiver
from receiving Intents if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage Application).Sometimes you want to determine if an component has registered for an intent. . For example you want to check if a certain intent receiver is available and in case a component is available you enable a functionality in your application.
This check can be done via the
PackageManager
class.The following example code checks if a component has registered for a certain intent. Construct your
Intent
as you desired to trigger it and pass it to the following method.public static boolean isIntentAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list =
mgr.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
Based on the result you can adjust your application. For example you could disable or hide certain menu items.
The following assumes that you have already basic knowledge in Android development. Please check the Android development tutorial to learn the basics.
The following exercise demonstrates how to use an explicit intent to start a sub-activity and how to send data to it.
This is the first part of an exercise continued in Section 9.1, “Target of this exercise”. The final solution can be found in Section 10, “Solution: Using intents”.
Create a new Android project called com.vogella.android.intent.explicit with an activity called
MainActivity
.Change the layout of the first activity to the following.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/inputforintent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="60dip"
android:text="First Activity"
android:textSize="20sp" >
</EditText>
<Button
android:id="@+id/startintent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/inputforintent"
android:layout_below="@+id/inputforintent"
android:onClick="onClick"
android:text="Calling an intent" />
</RelativeLayout>
Create a new layout called activity_result.xml which will be used in your second activity.
To create a new layout file select your project, right click on it and select Layout option.
→ → → → and select the Enter
activity_result.xml
as file name and press the button. Change your layout so that it is similar to the following XML file.<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/displayintentextra"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/returnValue"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
Add a new activity to the
AndroidManifest.xml
file.<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.vogella.android.first"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="Result Activity"
android:name=".ResultActivity" >
</activity>
</application>
</manifest>
Create the corresponding
ResultActivity
class based on the following example code.package com.vogella.android.intent.explicit;
import android.app.Activity;
import android.os.Bundle;
public class ResultActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_result);
}
}
This new activity will be started via the first activity, hence it is called a sub-activity.
Start the sub-activity via a button click from the
MainActivity
class. The following code gives some pointers how to solve this.package com.vogella.android.intent.explicit;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
EditText text = (EditText) findViewById(R.id.inputforintent);
// used later
String value = text.getText().toString();
// TODO 1 create new explicit Intent
// based on "ResultActivity.class"
// TODO 2 start second Activity with
// startActivity(intent);
}
}
Solve the TODO's in the source code so that the
ResultActivity
activity is started from theonClick()
method.Once you finished this part of the exercise, start your application an ensure that you can start the second activity.
The
MainActivity
class should pass the value of the EditText
view to the sub-activity. For this use the putExtra("yourKey", string)
on the Intent
object.In your
ResultActivity
sub-activity get the Bundle
with the intent data via thegetIntent().getExtras()
) method call.Get the value of the passed extra with the
getExtra("yourKey")
method on the bundle object which you got with the getExtras()
call.This value should be placed in the
TextView
with the displayintentextra
ID.This is the second part of an exercise which started in Section 8.1, “Target of this exercise”. An example solution for the activity can be found in Section 10, “Solution: Using intents”.
Continue to use the
com.vogella.android.intent.explicit
project.In the following exercise you transfer data back from your sub-activity second to the (
MainActivity
once the user selects the Back button.Add the implementation of the
finish()
method to the ResultActivity
class.@Override
public void finish() {
// TODO 1 create new Intent
// Intent intent = new Intent();
// TODO 2 read the data of the EditText field
// with the id returnValue
// TODO 3 put the text from EditText
// as String extra into the intent
// use editText.getText().toString();
// TODO 4 use setResult(RESULT_OK, intent);
// to return the Intent to the application
super.finish();
}
Solve all TODOs.
Use in
MainActivity
the startActivityForResult()
method to start the sub-activity. This allows you to use the onActivityResult()
method to receive data from the sub-activity. Extract the extra with the received bundle.Show a
Toast
with the extra data to validate that you correctly received it. The following code contains some pointer how to solve that.package com.vogella.android.intent.explicit;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
// constant to determine which sub-activity returns
private static final int REQUEST_CODE = 10;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
EditText text = (EditText) findViewById(R.id.inputforintent);
String string = text.getText().toString();
Intent i = new Intent(this, ResultActivity.class);
i.putExtra("yourkey", string);
// TODO 2.. now use
// startActivityForResult(i, REQUEST_CODE);
}
// TODO 3 Implement this method
// assumes that "returnkey" is used as key to return the result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnkey")) {
String result = data.getExtras().getString("returnkey");
if (result != null && result.length() > 0) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
}
}
}
After finishing the exercise in Section 9.1, “Target of this exercise” your activity coding should look similar to the following classes.
package com.vogella.android.intent.explicit;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class ResultActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_result);
Bundle extras = getIntent().getExtras();
String inputString = extras.getString("yourkey");
TextView view = (TextView) findViewById(R.id.displayintentextra);
view.setText(inputString);
}
@Override
public void finish() {
Intent intent = new Intent();
EditText editText= (EditText) findViewById(R.id.returnValue);
String string = editText.getText().toString();
intent.putExtra("returnkey", string);
setResult(RESULT_OK, intent);
super.finish();
}
}
package com.vogella.android.intent.explicit;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
// constant to determine which sub-activity returns
private static final int REQUEST_CODE = 10;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
EditText text = (EditText) findViewById(R.id.inputforintent);
String string = text.getText().toString();
Intent i = new Intent(this, ResultActivity.class);
i.putExtra("yourkey", string);
startActivityForResult(i, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnkey")) {
String result = data.getExtras().getString("returnkey");
if (result != null && result.length() > 0) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
}
}
}
The following exercise demonstrates the usage of implicit intents to trigger activities in your Android system.
Create a new Android application called de.vogella.android.intent.implicit with an activity called
CallIntentsActivity
.In this example you use a
Spinner
view to select which intent is triggered. For the content of theSpinner
you define static values.Create the following
intents.xml
file in the res/values
folder.<resources>
<string-array name="intents">
<item>Open Browser</item>
<item>Call Someone</item>
<item>Dial</item>
<item>Show Map</item>
<item>Search on Map</item>
<item>Take picture</item>
<item>Show contacts</item>
<item>Edit first contact</item>
</string-array>
</resources>
Change the layout file of the Activity to the following.
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alignmentMode="alignBounds"
android:columnCount="1" >
<Spinner
android:id="@+id/spinner"
android:layout_gravity="fill_horizontal"
android:drawSelectorOnTop="true"
>
</Spinner>
<Button
android:id="@+id/trigger"
android:onClick="onClick"
android:text="Trigger Intent">
</Button>
</GridLayout>
To be able to use certain intents you need to register for the required permission in your
AndroidManifest.xml
file. Ensure that your AndroidManifest.xml
contain the permissions from the followng listing.<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.intent.implicit"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" >
</uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE" >
</uses-permission>
<uses-permission android:name="android.permission.CAMERA" >
</uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".CallIntentsActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Change your activity class to the following code.
package de.vogella.android.intent.implicit;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class CallIntentsActivity extends Activity {
private Spinner spinner;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.intents, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void onClick(View view) {
int position = spinner.getSelectedItemPosition();
Intent intent = null;
switch (position) {
case 0:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.vogella.com"));
break;
case 1:
intent = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:(+49)12345789"));
break;
case 2:
intent = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:(+49)12345789"));
startActivity(intent);
break;
case 3:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:50.123,7.1434?z=19"));
break;
case 4:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:0,0?q=query"));
break;
case 5:
intent = new Intent("android.media.action.IMAGE_CAPTURE");
break;
case 6:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("content://contacts/people/"));
break;
case 7:
intent = new Intent(Intent.ACTION_EDIT,
Uri.parse("content://contacts/people/1"));
break;
}
if (intent != null) {
startActivity(intent);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
Toast.makeText(this, result, Toast.LENGTH_LONG);
}
}
}
If you start your application you see an list of buttons and if you press one of the buttons, your defined activities are started.
In the following exercise you register an activity as browser. This means that if an intent is triggered what someone wants to view an URL starting with http your activity will also be available to process this intent.
The example activity downloads the HTML source of this page and display this in a
TextView
.Create the Android project called de.vogella.android.intent.browserfilter with the activity called
BrowserActivity
.Register your activity to
Intent.Action_VIEW
action and the scheme "http" via the following changes in your AndroidManifest.xml
file The manifest also declares the permission to access the Internet.<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.intent.browserfilter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".BrowserActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
Change corresponding layout file to the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
</LinearLayout>
Change your activity class to the following code.
package de.vogella.android.intent.browserfilter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
public class BrowserActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To keep this example simple, we allow network access
// in the user interface thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.main);
Intent intent = getIntent();
TextView text = (TextView) findViewById(R.id.textView);
// To get the action of the intent use
String action = intent.getAction();
if (!action.equals(Intent.ACTION_VIEW)) {
throw new RuntimeException("Should not happen");
}
// To get the data use
Uri data = intent.getData();
URL url;
try {
url = new URL(data.getScheme(), data.getHost(), data.getPath());
BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
while ((line = rd.readLine()) != null) {
text.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Install your application. If you now trigger an intent to open an URL your should be able to select your own component. You can for example trigger this intent via the example from the implicit tutorials.
If you select you component the HTML code is loaded into your text view.
The following example shows how to pick an image from any registered photo application on Android via an intent.
Create a new Android project called de.vogella.android.imagepick with one activity calledImagePickActivity.
Change the
activity_main.xml
layout file to the following.<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="pickImage"
android:text="Button" >
</Button>
<ImageView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/icon" >
</ImageView>
</LinearLayout>
Change your activity class according to the following coding.
package de.vogella.android.imagepick;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class ImagePickActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.result);
}
public void pickImage(View View) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you run this application you can select an image from your image library on your Android phone and assign it to your
ImageView
.
No comments:
Post a Comment