Mobile Programming is a blogging site from where you can learn different programming concept for Android and iPhone.
Tuesday, December 10, 2013
Wednesday, October 23, 2013
Android-Screen-Anchoring Views
Anchoring Views
Anchoring could be easily achieved by using RelativeLayout. Consider the following main.xml containing five Button views embedded within theandroid:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
Anchoring Views
Anchoring Views
Observe the following attributes found in the various Button views:➤ layout_alignParentLeft — Aligns the view to the left of the parent view
➤ layout_alignParentRight — Aligns the view to the right of the parent view
➤ layout_alignParentTop — Aligns the view to the top of the parent view
➤ layout_alignParentBottom — Aligns the view to the bottom of the parent view
➤ layout_centerVertical — Centers the view vertically within its parent view
➤ layout_centerHorizontal — Centers the view horizontally within its parent view
Figure shows the activity when viewed in portrait mode.
When the screen orientation changes to landscape mode, the four buttons are aligned to the four edges of the screen, and the center button is centered in the middle of the screen with its width fully stretched (see Figure)
Android-Screen-Display Orientation
Display Orientation
Adapting To Display Orientation
One of the key features of modern smartphones is their ability to switch screen orientation, and Android is no exception. Android supports two screen orientations: portrait and landscape. By default,when you change the display orientation of your Android device, the current activity that is displayed will automatically redraw its content in the new orientation. This is because the onCreate() event of the activity is fi red whenever there is a change in display orientation.
Display Orientation
NOTE:- When you change the orientation of your Android device, your current activity is actually destroyed and then re-created.However, when the views are redrawn, they may be drawn in their original locations (depending on the layout selected). Figure shows one of the examples illustrated earlier displayed in both portrait and landscape mode.
Display Orientation
As you can observe in landscape mode, a lot of empty space on the right of the screen could be used.Furthermore, any additional views at the bottom of the screen would be hidden when the screen orientation is set to landscape.
Display Orientation
In general, you can employ two techniques to handle changes in screen orientation:➤ Anchoring — The easiest way is to “anchor” your views to the four edges of the screen. When the screen orientation changes, the views can anchor neatly to the edges.
➤ Resizing and repositioning — Whereas anchoring and centralizing are simple techniques to ensure that views can handle changes in screen orientation, the ultimate technique is resizing
each and every view according to the current screen orientation.
Android-Screen-Scroll View
Scroll View
A ScrollView is a special type of FrameLayout in that it enables users to scroll through a list of views that occupy more space than the physical display. The ScrollView can contain only one child view or ViewGroup, which normally is a LinearLayout.NOTE :-Do not use a ListView together with the
ScrollView. The ListView is designed for showing a list of related information and is optimized for dealing with large lists.The following main.xml content shows a ScrollView containing a LinearLayout, which in turn contains some Button and EditText views:
Scroll View
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
android:layout_height=”wrap_content”
android:orientation=”vertical”
>
Scroll View
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 1”
/>
Scroll View
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 2”
/>
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 3”
/>
android:layout_width=”fill_parent”
android:layout_height=”300px”
/>
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 4”
/>
Scroll View
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Button 5”
/>
Scroll View
Figure shows the ScrollView enabling the users to drag the screen upward to reveal the views located at the bottom of the screen.
Android-Screen-Frame Layout
Framelayout
The FrameLayout is a placeholder on screen that you can use to display a single view. Views that you add to a FrameLayout are always anchored to the top left of the layout. Consider the following content in main.xml:android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
Framelayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”This is my lovely dog, Ookii”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
/>
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
>
Framelayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
Framelayout
Here, you have a FrameLayout within a RelativeLayout. Within the FrameLayout, you embed an imageView. The UI is shown in Figure.NOTE:-This example assumes that the res/drawable-mdpi folder has an image
named ookii.png.
If you add another view (such as a Button view) within the FrameLayout, the view will overlap the previous view (see Figure)
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”This is my lovely dog, Ookii”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
/>
Framelayout
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
>
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
Framelayout
android:layout_height=”wrap_content”
android:text=”Print Picture”
/>
Android-Screen-Relative Layout
RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative to each other.Consider the following main.xml file:android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
RelativeLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Comments”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
/>
android:layout_width=”fill_parent”
android:layout_height=”170px”
android:textSize=”18sp”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
/>
RelativeLayout
android:layout_width=”125px”
android:layout_height=”wrap_content”
android:text=”Save”
android:layout_below=”@+id/txtComments”
android:layout_alignRight=”@+id/txtComments”
/>
android:layout_width=”124px”
android:layout_height=”wrap_content”
android:text=”Cancel”
android:layout_below=”@+id/txtComments”
android:layout_alignLeft=”@+id/txtComments”
/>
RelativeLayout
Notice that each view embedded within the RelativeLayout has attributes that enable it to alignwith another view. These attributes are as follows:
➤layout_alignParentTop
➤ layout_alignParentLeft
➤ layout_alignLeft
➤ layout_alignRight
➤ layout_below
➤ layout_centerHorizontal
The value for each of these attributes is the ID for the view that you are referencing. The preceding
XML UI creates the screen shown in Figure.
RelativeLayout
Android-Screen-Table Layout
TableLayout
The TableLayout groups views into rows and columns. You use theConsider the content of main.xml shown here:
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>
TableLayout
android:width =”120px”
/>
android:width=”200px” />
/>
android:password=”true”
/>
TableLayout
android:layout_height=”wrap_content”
android:text=”Remember Password”
/>
TableLayout
android:text=”Log In” />
TableLayout
Figure shows what the preceding looks like when rendered on the Android Emulator.
Note that in the preceding example, there are two columns and four rows in the TableLayout. The cell directly under the Password TextView is populated with an
Android-Screen-Linear Layout
Linear Layout
The LinearLayout arranges views in a single column or a single row. Child views can be arranged either
vertically or horizontally. To see how LinearLayout works, consider the following elements typically
contained in the main.xml file:
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
Linear Layout
In the main.xml file, observe that the root element is and it has a element contained within it. The element controls the order in which the views contained within it appear. For example, the width of the element fi lls the entire width of its parent (which is the screen in this case) using the fill_parent constant. Its height is indicated by the wrap_content constant, which means that its height is the height of its content (in this case, the text contained within it). If you don’t want to have the view occupy the entire row, you can set its
layout_width attribute to wrap_content, like this:
Linear Layout
< TextView
android:layout_width=”wrap_content
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
This will set the width of the view to be equal to the width of the text contained within it.
Consider the following layout:
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
android:layout_width=”105dp”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
android:layout_width=”160dp”
android:layout_height=”wrap_content”
android:text=”Button”
/>
Here, you set the width of both the TextView and Button views to an absolute value. In this case, the
width for the TextView is set to 105 density-independent pixels wide, and the Button to 160
densityindependent pixels wide. Figure 3-1 shows how the views look when viewed on an emulator with a
resolution of 320×480.
As you can see, in both emulators the widths of both views are the same with respect to the width of
the emulator. This demonstrates the usefulness of using the dp unit, which ensures that even if the
resolution of the target device is different, the size of the view relative to the device remains
unchanged
The preceding example also specifies that the orientation of the layout is vertical:
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
The default orientation layout is horizontal, so if you omit the android:orientation attribute, the
views will appear as shown in Figure.
In LinearLayout, you can apply the layout_weight and layout_gravity attributes to views contained
within it, as the following modifications to main.xml show:
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
android:layout_width=”105dp”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
android:layout_width=”160dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_gravity=”right”
android:layout_weight=”0.2”
/>
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textSize=”18sp”
android:layout_weight=”0.8”
/>
Figure shows that the button is aligned to the right of its parent (which is the LinearLayout) using
the layout_gravity attribute. At the same time, you use the layout_weight attribute to specify the
ratio in which the Button and EditText views occupy the remaining space on the screen. The total value
for the layout_weight attribute must be equal to 1.
Monday, October 14, 2013
Android-Veiw and Viewgroups
Views and Viewgroups
An activity contains Views and ViewGroups. A view is a widget that has an appearance on screen. Examples of views are buttons, labels, and text boxes. A view derives from the base class android.view.View.One or more views can be grouped together into a ViewGroup. A ViewGroup (which is itself a special type of view) provides the layout in which you can order the appearance and sequence of views. Examples of ViewGroups include LinearLayout and FrameLayout. A ViewGroup derives from the base class android.view.ViewGroup.
Views and Viewgroups
Android supports the following ViewGroups:➤ LinearLayout
➤ AbsoluteLayout
➤ TableLayout
➤ RelativeLayout
➤ FrameLayout
➤ ScrollView
The following sections describe each of these ViewGroups in more detail. Note that in practice it is common to combine different types of layouts to create the UI you want.
Android-Component of Screeen
Understanding the components of a Screen
you saw that the basic unit of an Android application is an activity. An activity
displays the user interface of your application, which may contain widgets like buttons, labels, text boxes, and so on. Typically, you define your UI using an XML fi le (e.g., the main.xml file located in the res/layout folder), which may look like this:
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
During run time, you load the XML UI in the onCreate() event handler in your Activity class, using
the setContentView() method of the Activity class:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
During compilation, each element in the XML fi le is compiled into its equivalent Android GUI class, with attributes represented by methods. The Android system then creates the UI of the activity when it is loaded.
you saw that the basic unit of an Android application is an activity. An activity
displays the user interface of your application, which may contain widgets like buttons, labels, text boxes, and so on. Typically, you define your UI using an XML fi le (e.g., the main.xml file located in the res/layout folder), which may look like this:
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
During run time, you load the XML UI in the onCreate() event handler in your Activity class, using
the setContentView() method of the Activity class:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
During compilation, each element in the XML fi le is compiled into its equivalent Android GUI class, with attributes represented by methods. The Android system then creates the UI of the activity when it is loaded.
Android-Component of Screen
Component of Screen
Understanding the components of a ScreenThe basic unit of an Android application is an activity. An activity displays the user interface of your application, which may contain widgets like buttons, labels, text boxes, and so on. Typically, you define your UI using an XML fi le (e.g., the main.xml file located in the res/layout folder), which may look like this:
Component of Screen
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
Component of Screen
During run time, you load the XML UI in the onCreate() event handler in your Activity class, using
the setContentView() method of the Activity class:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
During compilation, each element in the XML fi le is compiled into its equivalent Android GUI class, with attributes represented by methods. The Android system then creates the UI of the activity when it is loaded.
Sunday, October 6, 2013
Android-Display Notification
Displaying Notifications
So far, you have been using the Toast class to display messages to the user. While the Toast class is a handy way to show users alerts, it is not persistent. It flashes on the screen for a few seconds and then disappears. If it contains important information, users may easily miss it if they are not looking at the screen.For messages that are important, you should use a more persistent method. In this case, you should
use the NotificationManager to display a persistent message at the top of the device, commonly known as the status bar (sometimes also referred to as the notification bar). The following Try It Out demonstrates how.
Displaying Notifications on the Status Bar
Displaying Notifications
1. Using Eclipse, create a new Android project and name it Notifications.2. Add a new class file named NotificationView.java to the src folder of the project (see Figure). In addition, add a new notification.xml file to the res/layout folder as well.
Displaying Notifications
4. Populate the notification.xml file as follows:android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
android:layout_height=”wrap_content”
android:text=”Here are the details for the notification...” />
Displaying Notifications
5. Populate the NotificationView.java file as follows:package net.learn2develop.Notifications;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
public class NotificationView extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
//---look up the notification manager service---
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
//---cancel the notification that we started
nm.cancel(getIntent().getExtras().getInt(“notificationID”));
}
}
Displaying Notifications
6. Add the following statements in bold to the AndroidManifest.xml file:android:versionCode=”1”
android:versionName=”1.0”>
Displaying Notifications
7. Add the following statements in bold to the main.xml file:android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Display Notification” />
Displaying Notifications
8. Finally, add the following statements in bold to the MainActivity.java file:package net.learn2develop.Notifications;
import android.app.Activity;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
int notificationID = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.btn_displaynotif);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
displayNotification();
}
});
}
protected void displayNotification()
{
//---PendingIntent to launch activity if the user selects
// this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra(“notificationID”, notificationID);
PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.icon,“Reminder: Meeting starts in 5 minutes”,System.currentTimeMillis());
CharSequence from = “System Alarm”;
CharSequence message = “Meeting with customer at 3pm...”;notif.setLatestEventInfo(this, from, message, pendingIntent);
//---100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ms---
notif.vibrate = new long[] { 100, 250, 100, 500};
nm.notify(notificationID, notif);
}
}
8. Press F11 to debug the application on the Android Emulator.
9. Click the Display Notification button (see the top left of Figure) and a notification will appearon the status bar.
10. Clicking and dragging the status bar down will reveal the notification (see the right of Figure).
11. Clicking on the notification will reveal the NotificationView activity. This also causes ther.
Displaying Notifications
Displaying Notifications
How It WorksTo display a notification, you first created an Intent object to point to the NotificationView class:
//---PendingIntent to launch activity if the user selects
// this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra(“notificationID”, notificationID);
This intent will be used to launch another activity when the user selects a notification from the list of notifications.
In this example, you added a key/value pair to the Intent object so that you can tag the notification ID, identifying the notification to the target activity. This ID will be used to dismiss the notifications later.
You would also need to create a PendingIntent object. A PendingIntent object helps you to perform an action on your application’s behalf, often at a later time, regardless of whether your application is running or not. In this case, you initialized it as follows:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);
The getActivity() method retrieves a PendingIntent object and you set it using the following arguments:
➤ context — Application context
➤ request code — Request code for the intent
➤ intent — The intent for launching the target activity
➤ flags — The flags in which the activity is to be launched
You then obtain an instance of the NotificationManager class and create an instance of the Notification class:
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.icon,
“Reminder: Meeting starts in 5 minutes”,
System.currentTimeMillis());
The Notification class enables you to specify the notification’s main information when the notification first appears on the status bar. The second argument to the Notification constructor sets the “ticker text” on the status bar (see Figure)
Next, you set the details of the notification using the setLatestEventInfo() method:
CharSequence from = “System Alarm”;
CharSequence message = “Meeting with customer at 3pm...”;
notif.setLatestEventInfo(this, from, message, pendingIntent);
//---100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ms---
notif.vibrate = new long[] { 100, 250, 100, 500};
The preceding also sets the notification to vibrate the phone. Finally, to display the notification you use
the notify() method:
nm.notify(notificationID, notif);
When the user clicks on the notification, the NotificationView activity is launched. Here, you dismiss the notification by using the cancel() method of the NotificationManager object and passing it the ID
of the notification (passed in via the Intent object):
//---look up the notification manager service---
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
//---cancel the notification that we started
nm.cancel(getIntent().getExtras().getInt(“notificationID”));
Android-Adding Activity Categories
Adding Activity Categories
Adding Categories
You can group your activities into categories by using theandroid:versionCode=”1”
android:versionName=”1.0”>
Adding Activity Categories
In this case, the following code will invoke the MyBrowerActivity activity:Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“http://www.amazon.com”));
i.addCategory(“net.learn2develop.Apps”);
startActivity(i);
Adding Activity Categories
You add the category to the Intent object using the addCategory() method. If you omit the addCategory() statement, the preceding code will still invoke the MyBrowerActivity activity because it will still match the default category “android.intent.category.DEFAULT”. However, if you specify a category that does not match the category defined in the intent filter, it will not work:Intent i = new
Intent(“net.learn2develop.MyBrowser”,
Uri.parse(“http://www.amazon.com”));
//---this category does not match any in the intent-filter---
i.addCategory(“net.learn2develop.OtherApps”);
startActivity(i);
Adding Activity Categories
The preceding category (“net.learn2develop.OtherApps”) does not match any in the intent filter, so a run-time exception will be raised.If you add the preceding category in the intent filter of MyBrowerActivity, then the preceding code will work:
Adding Activity Categories
You can add multiple categories to an Intent object; for example, the following statements add the “net.learn2develop.SomeOtherApps” category to the Intent object:Intent i = new Intent(“net.learn2develop.MyBrowser”,
Uri.parse(“http://www.amazon.com”));
i.addCategory(“net.learn2develop.OtherApps”);
i.addCategory(“net.learn2develop.SomeOtherApps”);
startActivity(i);
Android-Intent Filters
Intent Filters
Using Intent Filters
Earlier, you saw how an activity can invoke another activity using the Intent object. In order for other activities to invoke your activity, you need to specify the action and category within theIntent Filters
Filters in More Details1. Using the Intents project created earlier, add a new class to the project and name it MyBrowserActivity.java. Also add a new XML file to the res/layout folder and name it browser.xml
Intent Filters
2. Add the following statements in bold to the AndroidManifest.xml file:android:versionCode=”1”
android:versionName=”1.0”>
Intent Filters
3. Add the following statements in bold to the main.xml file:android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Web Browser” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Make Calls” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Show Map” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Choose Contact” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Launch My Browser” />
Intent Filters
4. Add the following statements in bold to the MainActivity.java file:package net.learn2develop.Intents;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1, b2, b3, b4, b5;
int request_Code = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---Web browser button---
b1 = (Button) findViewById(R.id.btn_webbrowser);
b1.setOnClickListener(new OnClickListener()
{
//...
});
//---Make calls button---
b2 = (Button) findViewById(R.id.btn_makecalls);
b2.setOnClickListener(new OnClickListener()
{
//...
});
//---Show Map button---
b3 = (Button) findViewById(R.id.btn_showMap);
b3.setOnClickListener(new OnClickListener()
{
//...
});
//---Choose Contact button---
b4 = (Button) findViewById(R.id.btn_chooseContact);
b4.setOnClickListener(new OnClickListener()
{
//...
});
b5 = (Button) findViewById(R.id.btn_launchMyBrowser);
b5.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new
Intent(“net.learn2develop.MyBrowser”);
i.setData(Uri.parse(“http://www.amazon.com”));
startActivity(i);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
//...
}
}
Intent Filters
5. Add the following statements in bold to the browser.xml file:android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
6. Add the following statements in bold to the MyBrowserActivity.java file:
package net.learn2develop.Intents;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyBrowserActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browser);
Uri url = getIntent().getData();
WebView webView = (WebView) findViewById(R.id.WebView01);
webView.setWebViewClient(new Callback());
webView.loadUrl(url.toString());
}
private class Callback extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return(false);
}
}
}
Intent Filters
6. Press F11 to debug the application on the Android Emulator.7. Click the Launch my Browser button and you should see the new activity displaying the Amazon.com web page (see Figure).
Intent Filters
How It WorksIn this example, you created a new activity named MyBrowserActivity. You first needed to declare it in the AndroidManifest.xml file:
Intent Filters
In the.DEFAULT” category. If not, your activity will not be callable by others. The element specifies the type of data expected by the activity. In this case, it expects the data to start with the “http://” prefix.
The preceding intent filter could also be rewritten as follows:
Writing the intent filter this way makes it much more readable and logically groups the action, category,and data within an intent filter.
If you now use the ACTION_VIEW action with the data shown here, Android will display a selection (as shown in Figure):
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“http://www.amazon.com”));
startActivity(i);
You can choose between using the Browser application or the Intents application that you are currently building.
Android-Intent Object
Intent Object
Understanding the Intent ObjectSo far, you have seen the use of the Intent object to call other activities. This is a good time to recap and gain a more detailed understanding of how the Intent object performs its magic. First, you see that you can call another activity by passing its action to the constructor of an Intent object:
startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
Intent Object
The action (in this example “net.learn2develop.ACTIVITY2”) is also known as the component name.This is used to identify the target activity/application that you want to invoke. You can also rewrite the component name by specifying the class name of the activity if it resides in your project, like this:
startActivity(new Intent(this, Activity2.class));
You can also create an Intent object by passing in an action constant and data, such as the following:
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“http://www.amazon.com”));
startActivity(i);
Intent Object
The action portion defines what you want to do, while the data portion contains the data for the target activity to act upon. You can also pass the data to the Intent object using the setData() method:Intent i = new
Intent(android.content.Intent.ACTION_VIEW);
i.setData(Uri.parse(“http://www.amazon.com”));
Intent Object
In this example, you indicate that you want to view a web page with the specified URL. The Android OS will look for all activities that are able to satisfy your request. This process is known as intent resolution. The next section discusses in more detail how your activities can be the target of other activities.For some intents, there is no need to specify the data. For example, to select a contact from the Contacts application, you specify the action and then indicate the MIME type using the setType() method:
Intent i = new Intent(android.content.Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
Intent Object
The setType() method explicitly specifies the MIME data type to indicate the type of data to return. The MIME type for ContactsContract.Contacts.CONTENT_TYPE is “vnd.android.cursor.dir/contact”.Besides specifying the action, the data, and the type, an Intent object can also specify a category. A category groups activities into logical units so that Android can use it for further filtering. The next section discusses categories in more details. To summarize, an Intent object can contain the following information:
➤ Action
➤ Data
➤ Type
➤ Category
Android-Calling Built-In Applications Using Intents
Calling Built-In Applications Using Intents
Until this point, you have seen how to call activities within your own application. One of the key aspects of Android programming is using the intent to call activities from other applications. In particular, your application can call the many built-in applications that are included with an Android device. For example, if your application needs to enable a user to call a particular person saved in the Contacts application, you can simply use an Intent object to bring up the Contacts application, from which the user can select the person to call. This enables your application to present a consistent user experience, and enables you to avoid building another application to retrieve all the contacts in the Contacts application.The following Try It Out demonstrates how to call some of the built-in applications commonly found on an Android device.
Calling Built-In Applications Using Intents
1. Using Eclipse, create a new Android project and name it Intents.2. Add the following statements in bold to the main.xml file:
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Web Browser” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Make Calls” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Show Map” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Choose Contact” />
Calling Built-In Applications Using Intents
3. Add the following statements in bold to the MainActivity.java file:package net.learn2develop.Intents;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1, b2, b3, b4;
int request_Code = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---Web browser button---
b1 = (Button) findViewById(R.id.btn_webbrowser);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“http://www.amazon.com”));
startActivity(i);
}
});
//---Make calls button---
b2 = (Button) findViewById(R.id.btn_makecalls);
b2.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_DIAL,
Uri.parse(“tel:+651234567”));
startActivity(i);
}
});
//---Show Map button---
b3 = (Button) findViewById(R.id.btn_showMap);
b3.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“geo:37.827500,-122.481670”));
startActivity(i);
}
});
//---Choose Contact button---
b4 = (Button) findViewById(R.id.btn_chooseContact);
b4.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(i,request_Code);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code)
{
if (resultCode == RESULT_OK)
{
Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_SHORT).show();
Intent i = new Intent(
android.content.Intent.ACTION_VIEW,
Uri.parse(data.getData().toString()));
startActivity(i);
}
}
}
}
4. Press F11 to debug the application on the Android Emulator.
5 . Click the Web Browser button to load the Browser application on the emulator (see Figure)
6. Click the Make Calls button and the Phone application will load.
7 . Similarly, to load the Maps application, shown in Figure click the Show Map button.
8. Click the Choose Contact application to show a list of contacts that you can select (see Figure). Selecting a contact will show details about that contact.
Calling Built-In Applications Using Intents
Calling Built-In Applications Using Intents
How It Works
In this example, you saw how you can use the Intent class to invoke some of the built-in applications in Android (such as Maps, Phone, Contacts, and Browser).In Android, intents usually come in pairs: action and data. The action describes what is to be performed, such as editing an item, viewing the content of an item, and so on. The data specifies what is affected, such as a person in the Contacts database. The data is specified as an Uri object.
Some examples of action are as follows:
➤ACTION_VIEW
➤ ACTION_DIAL
➤ ACTION_PICK
Some examples of data include the following:
➤ http://www.google.com
➤ tel:+651234567
➤ geo:37.827500,-122.481670
➤ content://contacts
Collectively, the action and data pair describes the operation to be performed. For example, to dial a phone number, you would use the pair ACTION_DIAL/tel:+651234567. To display a list of contacts stored in your phone, you use the pair ACTION_VIEW/content://contacts. To pick a contact from the list of contacts, you use the pair ACTION_PICK/content://contacts.
In the fi rst button, you create an Intent object and then pass two arguments to its constructor — the action and the data:
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“http://www.amazon.com”));
startActivity(i);
The action here is represented by the android.content.Intent.ACTION_VIEW constant. You use the parse() method of the Uri class to convert an URL string into an Uri object.
The android.content.Intent.ACTION_VIEW constant actually refers to the “android.intent.action.VIEW” action, so the preceding could be rewritten as follows:
Intent i = new Intent(“android.intent.action.VIEW”,
Uri.parse(“http://www.amazon.com”));
startActivity(i);
The preceding code snippet can also be rewritten like this:
Intent i = new Intent(“android.intent.action.VIEW”);
i.setData(Uri.parse(“http://www.amazon.com”));
startActivity(i);
Here, you set the data separately using the setData() method.
For the second button, you dial a specific number by passing in the telephone number in the data portion:
Intent i = new Intent(“android.intent.action.VIEW”);
i.setData(Uri.parse(“http://www.amazon.com”));
startActivity(i);
Calling Built-In Applications Using Intents
In this case, the dialer will display the number to be called. The user must still press the dial button to dial
the number. If you want to directly call the number without user intervention, change the action as follows:Intent i = new Intent(android.content.Intent.ACTION_CALL,
Uri.parse(“tel:+651234567”));
startActivity(i);
If you simply want to display the dialer without specifying any number, simply omit the data portion, like this:
Intent i = new Intent(android.content.Intent.ACTION_DIAL);
startActivity(i);
The third button displays a map using the ACTION_VIEW constant:
Here, instead of using “http” you use the “geo” scheme.
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(“geo:37.827500,-122.481670”));
startActivity(i);
The fourth button invokes the Contacts application to enable the user to pick a contact. Because you are asking the user to select a contact, you need the Contacts application to return a value; in this case, you need to set the type of data to indicate what kind of data needs to be returned:
Intent i = new Intent(android.content.Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(i,request_Code);
If you want to view and select only those contacts with a phone number, you could set the type as follows:
i.setType( ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
In this case, the contacts and their phone numbers are displayed (see Figure).
Calling Built-In Applications Using Intents
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code)
{
if (resultCode == RESULT_OK)
{
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(data.getData().toString()));
startActivity(i);
}
}
}
In the case of the Contacts application, when you choose a particular contact (using the ACTION_PICK constant), an URL containing the contact selected is returned, like this:
content://com.android.contacts/contacts/loopup/0r1-1234567890/1
Obtaining this URL is not very useful unless you know what to do with it. Therefore, in this case, you can create another Intent object to view it:
Intent i = new Intent( android.content.Intent.ACTION_VIEW,
Uri.parse(data.getData().toString()));
startActivity(i);
This will show details about the selected contact.
Android-Passing Data Using an Intent Object
Passing Data Using an Intent Object
Besides returning data from an activity, it is also common to pass data to an activity. For example, in the previous example you may want to set some default text in the EditText view before the activity is displayed. In this case, you can use the Intent object to pass the data to the target activity. The following Try It Out shows you how.Passing Data Using an Intent Object
Passing Data to the Target Activity1. Using the same project created in the previous section, add the following statements in bold to the MainActivity.java file:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
//startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
//startActivity(new Intent(this, Activity2.class));
/*
startActivityForResult(new Intent(
“net.learn2develop.ACTIVITY2”),
request_Code);
*/
Intent i = new Intent(“net.learn2develop.ACTIVITY2”);
Bundle extras = new Bundle();
extras.putString(“Name”, “Your name here”);
i.putExtras(extras);
startActivityForResult(i, 1);
}
return false;
}
Passing Data Using an Intent Object
2. Add the following statements in bold to Activity2.java:public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String defaultName=””;Bundle extras = getIntent().getExtras();
if (extras!=null)
{
defaultName = extras.getString(“Name”);
}
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username); txt_username.setHint(defaultName);
//---get the OK button---
Button btn = (Button) findViewById(R.id.btn_OK);
//---event handler for the OK button---
btn.setOnClickListener(new View.OnClickListener()
{
//...
});
}
Passing Data Using an Intent Object
3. Press F11 to debug the application on the Android Emulator. When you click the center button of the directional keypad, notice that the EditText view in the target activity displays the hint text (see Figure).Passing Data Using an Intent Object
How It WorksTo use the Intent object to carry data to the target activity, you made use of a Bundle object:
Bundle extras = new Bundle();
extras.putString(“Name”, “Your name here”);
i.putExtras(extras);
Passing Data Using an Intent Object
A Bundle object is basically a dictionary object that enables you to set data in key/value pairs. In this case, you created a key named Name and assigned it a value of “Your name here”. The Bundle object is then added to the Intent object using the putExtras() method.In the target activity, you first use the getIntent() method to obtain the intent that started the activity.
You then use the getExtras() method to obtain the Bundle object:
Bundle extras = getIntent().getExtras();
if (extras!=null)
{
defaultName = extras.getString(“Name”);
}
The getString() method retrieves the Name key from the Bundle object. The string retrieved is then
assigned to the EditText view using the setHint() method:
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
txt_username.setHint(defaultName);
Android-Returning Result from intent
Returning Results from an Intent
The startActivity() method invokes another activity but does not return a result to the current activity. For example, you may have an activity that prompts the user for username and password. The information entered by the user in that activity needs to be passed back to the calling activity for further processing. If you need to pass data back from an activity, you should instead use the startActivityForResult() method. The following Try It Out demonstrates this.Returning Results from an Intent
1. Using the same project created in the previous section, add the following statements in bold to the main.xml file:android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
android:layout_height=”wrap_content”
android:text=”Please enter your name” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”OK” />
Returning Results from an Intent
2. Add the following statements in bold to Activity2.java:package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Activity2 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
//---get the OK button---
Button btn = (Button) findViewById(R.id.btn_OK);
//---event handler for the OK button---
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
}
}
Returning Results from an Intent
3. Add the following statements in bold to the MainActivity.java file:package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.KeyEvent;
import android.widget.Toast;
import android.content.Intent;
public class MainActivity extends Activity {
String tag = “Events”;
int request_Code = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---hides the title bar---
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Log.d(tag, “In the onCreate() event”);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
//startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
//startActivity(new Intent(this, Activity2.class));
startActivityForResult(new Intent(“net.learn2develop.ACTIVITY2”),request_Code);
}
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_SHORT).show();
}
}
}
public void onStart() { //... }
public void onRestart() { //... }
public void onResume() { //... }
public void onPause() { //... }
public void onStop() { //... }
public void onDestroy() { //... }
}
Returning Results from an Intent
4. Press F11 to debug the application on the Android Emulator. When the first activity is loaded, click the center button on the directional pad. Activity2 will now be loaded. Enter your name (see Figure 2-16) and click the OK button. You will see that the first activity now displays the name you have entered using the Toast class.Returning Results from an Intent
How It WorksTo call an activity and wait for a result to be returned from it, you need to use the
startActivityForResult() method, like this:
startActivityForResult(new Intent(“net.learn2develop.ACTIVITY2”),request_Code);
In addition to passing in an Intent object, you need to pass in request code as well. The request code is simply an integer value that identifies an activity you are calling. This is needed because when an activity returns a value, you must have a way to identify it. For example, you may be calling multiple activities at the same time and some activities may not return immediately (for example, waiting for a reply from a server). When an activity returns, you need this request code to determine which activity is actually returned.
NOTE If the request code is set to -1, then calling it using the
startActivityForResult() method is equivalent to calling it using
the startActivity() method. That is, no result will be returned.
In order for an activity to return a value to the calling activity, you use an Intent object to send data back via the setData() method:
Intent data = new Intent();
//---get the EditText view---
EditText txt_username = (EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
The setResult() method sets a result code (either RESULT_OK or RESULT_CANCELLED) and the data (an Intent object) to be returned back to the calling activity. The finish() method closes the activity and returns control back to the calling activity.
In the calling activity, you need to implement the onActivityResult() method, which is called whenever an activity returns:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
}
Here, you check for the appropriate request code and display the result that is returned. The returned result is passed in via the data argument; and you obtain its details through the getData() method.
Wednesday, October 2, 2013
Android-Filter Collision
Filter Collision
Resolving Intent Filter CollisionIn the Activity Linking section, you learned that the
Filter Collision
android:versionCode=”1”
android:versionName=”1.0”>
<! -- android:theme=”@android:style/Theme.Dialog” -- >
Filter Collision
If you call the startActivity() method with the following intent, then the Android OS will display a selection as shown in Figure.startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
If you check the “Use by default for this action” item and then select an activity, then the next time the intent “net.learn2develop.ACTIVITY2” is called again, it will always launch the previous activity that you have selected.
To clear away this default, go to the Settings application in Android and select Applications ➪ Manage applications and select the application name. When the details of the application are shown, scroll down to the bottom and click the Clear defaults button.
Filter Collision
Filter Collision
Android-Activity Linking
Activity Linking
Linking Activities using intents
An Android application can contain zero or more activities. When your application has more than one activity, you may need to navigate from one activity to another. In Android, you navigate between activities through what is known as an intent.The best way to understand this very important but somewhat abstract concept in Android is to experience it firsthand and see what it helps you to achieve.
The following Try It Out shows how to add another activity to an existing project and then navigate between the two activities.
Linking Activities
Follow following steps to link Activity
1. Using the Activities project created earlier, add the following statements in bold to the AndroidManifest.xml file:android:versionCode=”1”
android:versionName=”1.0”>
android:theme=”@android:style/Theme.Dialog” >
Linking Activities
2. Right click on the package name under the src folder and select New ➪ Class (see Figure 2-10).3. Name the new class file Activity2 (see Figure 2-11) and click Finish.
4. Make a copy of the main.xml file by right-clicking on it and selecting Copy. Then, right-click on the res/layout folder and select Paste. Name the file activity2.xml. The res/layout folder will now contain the activity2.xml file (see Figure)
Linking Activities
Modify the activity2.xml file as follows:android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:layout_height=”wrap_content”
android:text=”This is Activity 2!”
/>
>
6. In the Activity2.java file, add the following statements in bold:
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
public class Activity2 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
}
}
7. Modify the MainActivity.java file as shown in bold:
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.KeyEvent;
import android.content.Intent;
public class MainActivity extends Activity {
String tag = “Events”;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---hides the title bar---
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Log.d(tag, “In the onCreate() event”);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
}
return false;
}
public void onStart() { //... }
public void onRestart() { //... }
public void onResume() { //... }
public void onPause() { //... }
public void onStop() { //... }
public void onDestroy() { //... }
}
8. Press F11 to debug the application on the Android Emulator. When the first activity is loaded, click the center of the directional pad (see Figure ; on a real device this can be achieved by pressing down the trackball). The second activity will now be loaded.
Linking Activities
How It Works
As you have learned, an activity is made up of a UI component (for example, main.xml) and a class component (for example, MainActivity.java). Hence, if you want to add another activity to a project, you need to create these two components.In the AndroidManifest.xml file, specifically you have added the following:Linking Activities
Here, you have added a new activity to the application. Note the following:➤ The name of the new activity added is “Activity2”.
➤ The label for the activity is named “Activity 2”.
➤ The intent filter name for the activity is “net.learn2develop.ACTIVITY2”. Other activities that wish to call this activity will invoke it via this name. Ideally, you should use the reverse domain name of your company as the intent filter name in order to reduce the chances of another application having the same intent filter. The next section discusses what happens when two or more activities have the
same intent filter.
➤ The category for the intent filter is “android.intent.category.DEFAULT”. You need to add this to the intent filter so that this activity can be started by another activity using the startActivity() method (more on this shortly).
In the MainActivity.java file, you implemented the onKeyDown event handler. This event is fired whenever the user presses one of the keys on the device. When the user presses the center key on the directional pad (as represented by the KeyEvent.KEYCODE_DPAD_CENTER constant), you use the startActivity()
method to display Activity2 by creating an instance of the Intent class and passing it the intent filter name of Activity2 (which is net.learn2develop.ACTIVITY2):
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
startActivity(new Intent(“net.learn2develop.ACTIVITY2”));
}
return false;
}
Linking Activities
Activities in Android can be invoked by any application running on the device. For example, you can create a new Android project and then display Activity2 by using its net.learn2develop.ACTIVITY2 intent filter. This is one of the fundamental concepts in Android that enables an application to invoke another easily.If the activity that you want to invoke is defined within the same project, you can rewrite the preceding statement like this:
startActivity(new Intent(this, Activity2.class));
However, this approach is applicable only when the activity you want to display is within the same project as the current activity.
Subscribe to:
Posts (Atom)
Upload UIImage as base64 String
Upload UIImage as Base64 String (Upload UIImage as string) //Select Pic From Camera or Gallery @objc func btnPro...
-
Calling Built-In Applications Using Intents Until this point, you have seen how to call activities within your own application. One of th...
-
ADA-Algorithm Design and Analysis Notes Algorithm Definition Step by step procedure designed to perform an operation, and which...