1 / 34

Activities

Activities. Definitions Process : An executing android (Linux) application with a unique PID running its own Dalvik JVM, having one or more threads Task : A collection of bundled Activities, which can span processes Activity : A discrete chunk of functionality

edmund
Télécharger la présentation

Activities

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Activities • Definitions • Process: An executing android (Linux) application with a unique PID running its own Dalvik JVM, having one or more threads • Task: A collection of bundled Activities, which can span processes • Activity: A discrete chunk of functionality • Fragment: A component of an activity that corresponds to a view • Activities • Building block of a user interface (UI), often, but not always, corresponding to one or more single UI screen • In Java, we create an activity by extending the Activity class • Activities can sometimes be • Faceless (without a visible UI: Speech Recognition for example) • Present themselves in a floating window • Return values to other activities (startActivityForResult)

  2. Activities (Android searches for the best match) Note: Activities originate within APKs A single APK can spawn multiple processes

  3. Activity Life Cycle Activity Life Cycle • The Activity class contains predefined listener functions that handle system events • System events occur when the activity changes life cycle states • Developers override these methods if they need to customize event handling • Event handlers release and allocate resources, stop network connections, etc.

  4. Application Design • Layout:Design the various screens that users see, where each screen corresponds to single Activity • Transitions: Design the transitionsbetween views (animations) • External applications:Determine exposure to other activities • Security permissions:Decide needed security permissions • Background services: Design mechanisms to exchange data, listen for connections, and periodically download information from a server • Content providers: Design application long-term data storage requirements, mechanisms for storage, and content providers providing data access wrappers • Connections:Determine how activities and services tie together

  5. Steps to developing an Activity • Create the Eclipse Android project • Define the package name for you application (ex: com.acorns) • Create the manifest file, which declares activities, intents, services, content providers, and and defines required permissions • Define resources as subfolders of the res directory. • Store multimedia components and other files as assets, raw data, or drawables • Create a new class in the project extending Activity, along with any helper classes needed • Override the onCreate() method to • Specify a default View for the Activity. • Code and register/attach the handlers that respond to user events • Override the other predefined methods as needed • Release resources on state changes • Interact with other classes • Utilize Android system resources • Determine external activity interactions • Create content provider interfaces • Create alternative menus • Launch activities using intent objects

  6. Activities versus Tasks Activities • A class in the Android API • An encapsulation of a particular user operation • Defined within a single APK • Normally associated with a single user interface view • An self-contained execution context Tasks • A bundled collection of activities • Can span multiple processes • Each has a its own history stack • Stack of activities launched by the users • Multiple tasks exist and moved from foreground to background (long press on home button)

  7. Android Activity Framework Activities can interact with • Content Providers: An activity that provides a uniform access to data resources. Provides level of abstraction for stored data, which is accessible by multiple applications • Alternative Menus:Menu items inserted into an activities user interface from remote activities • Services: Background processes not associated with a view. They run independent of any activity. • Notifications: The User notification framework enables signaling users without interrupting their current activity. For instance flashing lights can indicate an incoming call.

  8. Activity Execution • An Activity, loaded by the Android OS, calls appropriate methods based on user interaction. • On start up • A default view (empty screen) is presented to the activity • The overridden onCreate() method specifies a top level GUI screen, which likely contains sub-views, and UI listeners to react to user events. • User events can trigger changes to the screen view, or interactions with application data • Each Activity performs its own actions, but can launch other Activities with Intent objects

  9. Fragments A fully reusable application component with its own lifecycle • Enables creation of a series of user interfaces accommodating different device features • Each fragment is self-contained and reusable by application components • Enables a more flexible application design

  10. Fragment Example Ctrl F11 switches the emulator between landscape and portrait

  11. Activity Example with Fragments public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Configuration config = getResources().getConfiguration(); FragmentManagerfragmentManager = getFragmentManager(); FragmentTransactiontransaction = fragmentManager.beginTransaction(); if (config.orientation== Configuration.ORIENTATION_LANDSCAPE) { transaction.replace(android.R.id.content, new Landscape()); } else { transaction.replace(android.R.id.content, new Portrait()); } transaction.commit(); } } Note:Android.R.id.content refers to the root element of a view without having to know it’s actual ID value

  12. Landscape and Portrait Fragments public class Landscape extends Fragment { @Override public View onCreateView(LayoutInflaterinflater, ViewGroup root, Bundle b) { return inflater.inflate( R.layout.lm_fragment, root, false); } } public class Portrait extends Fragment { @Override public View onCreateView(LayoutInflaterinflater, ViewGroup root, Bundle b) { return inflater.inflate( R.layout.pm_fragment, root, false); } } root: if Non-null, the view to which the fragment is attached Inflate false: don’t use root layout parameters

  13. Fragment Views File: res/layout/lm_fragment.xml File: res/layout/pm_fragment.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation= "horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#666666"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/portrait_message" android:textColor="#000000" android:textSize="20sp" /> <!-- More GUI components --> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#7bae16"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/landscape_message" android:textColor="#000000" android:textSize="20sp" /> <!-- More GUI components --> </LinearLayout>

  14. res/layout/activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:baselineAligned="false" android:orientation="horizontal"> <fragment android:name="com.example.fragments" android:id="@+id/lm_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.fragments" android:id="@+id/pm_fragment" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>

  15. res/values/strings.xml file <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">MyFragments</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="landscape_message"> This is Landscape mode fragment </string> <string name="portrait_message"> This is Portrait mode fragment </string> </resources>

  16. Working with Fragments FragmentManagerfragmentManager = getFragmentManager(); FragmentTransactionxAction = fragmentManager.beginTransaction(); . . . xAction.commit(); • Possible transactions • Add(), attach(), detatch(), remove(), replace(), hide(), show() • addToBackStack() • Finding fragment from activity or activity from fragment • View listView = getActivity().findViewById(R.id.list); • From fragmentManager: findFragmentById() or findFragmentbyTag() • Communication fragment to activity • Define callback interface in fragment implemented in the activity When using replace, a tag string can be designated for later searching

  17. Intents • Intents (Android's mechanism for handling inter-process communication) • Describe what should be done; commonly to launch an activity • Target specific activities or services or can be a system wide broadcast • Inform applications of events and alarms • Initiated either from the system or from user activities • Activities & Broadcast Receivers • Define the intents that they can service • Provide the logic to respond to intents when received • System: Match an intent with a receiver that can best satisfy the request • Examples • Activity events ( launch app possibly with data to process, press button) • Hardware state changes (acceleration change, screen off, etc.) • Incoming data (Receiving call) • Communication between activities (launch with reply expected) • Initiate Android services: Dialing a number; Sending a text • Broadcast that an event occurred

  18. Intents A user activity requests a specific action Home Photo Gallery Contacts Based on the intent, the system picks a matching activity for that action “Pick photo” GMail Chat Newly defined activities can use and respond to intent data Blogger Blogger Definition: Inter-process message facility for launching/ communicating with system or application activities.

  19. Intent object starts the ViewContent Activity Intent Processing User starts your app onRestart() onCreate() BrowseContents Running • Initiate an activity • Instantiate an instance of the Intent class to request a launch of some Activity or Service • Android finds a matching activity • Android schedules that Activity to run • For Activities, its onCreate method is called • Both the system and applications use Intents to launch activities New() User clicks on an object to edit Intent object starts the EditContent Activity onCreate() User clicks back button EditContent running Note: The red lines are Android OS initiated events; the blue lines are application initiated events

  20. Launchable Android Provided Activities • Open a browser window public static void invokeWebBrowser(Activity activity) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.google.com")); activity.startActivity(intent); } • Call a telephone number public static void call(Activity activity) { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:555-555-5555")); activity.startActivity(intent); } • Present a phone dialer public static void dial(Activity activity) { Intent intent = new Intent(Intent.ACTION_DIAL); activity.startActivity(intent); }

  21. Intents with results • Launching Intents • Explicitly: by reference to the activity’s class name • Implicit: By name, category, data type, or data URI • Broadcast Intents: Broadcast notification of an event that occurred. Receiver modules listening respond appropriately • Sticky Intents: The broadcast result persists. Activities can obtain the most recent result without implementing a receiver. Examples: battery charging status, network connection • Intents expecting return value: The launched activity produces a result handled by a callback method in the initiating activity

  22. Resolving Intents Manifest data tag <data android:host="string"      android:mimeType="string"      android:path="string"      android:pathPattern="string"      android:pathPrefix="string"      android:port="string"      android:scheme="string" /> • Action:Action must match the registered a manifest intent filter, if one exists • Data: Intent carrying data must match intent filter specification • Host Name: for example, google.com • Mime type: vnd.android.cursor.dir/* or vnd.android.cursor.item/10 matches all or specific rows of an android SQL cursor • Path, Path Patter, Path Prefix: must match if specified (ex: data authority/note) • Data authority: match filter specification (ex: com.google.provider.NotePad) • Port: listening port on the host machine • Scheme: examples: content or http

  23. Explicit Activity launch Manifest Activity Registration <activity android:name="ViewActivity" android:label="View Tests"> <intent-filter><action android:name = "com.acorns.intent.action.ShowView"/> <category android:name ="android.intent.category.DEFAULT" /> </intent-filter></activity> Basic Java Code public class ViewActivity extends Activity { @Override public void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.main); Intent intent = this.getIntent(); if (intent==null) { log.d("ViewActivity","invoked without an intent"); } } } Launch public static void invokeApplication(Activity parentActivity) {parentActivity.startActivity(new Intent("com.acorns.intent.action.ShowView")); }

  24. Intent Filters in XML <activity android:name=".MyBlogViewerActivity“> <!– View website content --> <intent-filter><action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http" android:host="blog.radioactiveyak.com"/> </intent-filter> </activity> <activity android:name=".NostromoController“> <!-- Advertise capabilities --> <intent-filter android:label="@string/Nuke_From_Orbit"> <action android:name="com.pad.nostromo.NUKE_FROM_ORBIT"/> <data android:mimeType="vnd.moonbase.cursor.item/*"/> <category android:name="android.intent.category.ALTERNATIVE"/> <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> </intent-filter> </activity> Launches must match one of the actions, and all categories ALTERNATIVE: display on alternative menu SELECTED_ALTERNATIVE: User chooses from an item list

  25. Intent Categories Indicate to Android the general nature of an activity • CATEGORY_DEFAULT: invokable through implicit intents • CATEGORY_BROWSABLE: Will not violate browser security restructions • CATEGORY_TAB: Embeddable in a tabbed view of a parent activity • CATEGORY_ALTERNATIVE: Support alternative menus • CATEGORY_SELECTED_ALTERNATIVE: Alternative editor for data • CATEGORY_LAUNCHER: Listable on the launcher screen • CATEGORY_HOME: The home screen view (One per device) • CATEGORY_PREFERENCE: Shown on the preference screen • CATEGORY_GADGET: Embeddable in a parent activity

  26. Implicit Launch of an Activity Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368")); PackageManager pm = getPackageManager(); ComponentName cn = intent.resolveActivity(pm); if (cn == null) // Check if matching activity is available { Uri uri = Uri.parse("market://search?q=pname:com.app.name"); Intent intent = new Intent(Intent.ACTION_VIEW).setData(uri); if (intent.resolveActivity(pm) != null) startActivity(marketIntent); else Log.d(TAG, "Activity not available on the Android market"); } else startActivity(intent);

  27. Intent Objects Android invokes activities compatible with an intent • Definitions • Explicit: Includes a class and package name (intent.setComponent(name)) • Implicit: Relies on action and data • Action • Package string: new Intent("com.acorns.intent.action.ShowView"); • Generic Action: new Intent(Intent.ACTION_VIEW); • Data URI (A URI pointer to data) • Intent intent = new Intent(Intent.ACTION_CALL); • Intent.setData(Uri.parse(tel:555-555-5555)); • Key/value extra data elements • Bundle extra = intent.getExtras(); • (Bitmap) extra.getExtras().get("data");

  28. Bundling an Intent • Code to add bundleable objectsBundle more = new Bundle(); // a bundle contains key/value pairs more.putString("someKey", "someString"); intent.putExtra("bundleKey", more); // A bundle of extra items intent.putExtra("anotherKey", 3.5); // A single extra item • Updating the bundle • If a bundle exists, Android adds additional key/data pairs • If a bundle doesn't exist, create one and copy key/data pairs to it • Overloaded putExtra() methods for adding • booleans, ints, doubles, floats, strings, arrays, serializable objects, parcelable objects, bundles, additional intents • Note: A parcelable interface defines how an object should be serialized if it is to be written/read from persistent storage

  29. Intents with Results // Launch the sub activity expecting a result private static final int SELECT_HORSE = 1, SELECT_GUN = 2; private void startSubActivity(int option) { startActivityForResult(new Intent(this, Other.class), option); } // Receive Result with a call back @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch(requestCode) { case (SELECT_HORSE): selectedHorse = data.getData(); break; case (SELECT_GUN): selectedGun = data.getData(); break; } } }

  30. Linkify Facility to create clickable links in text that launches activities • Linkify a view in code: TextView text = (TextView)FindViewById(R.id.myTextView);Linkify.addLinks(text, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES); • Linkify in XML<TextView android.text="@string/linkifyMe" android:autolink="phone|email" android:layout_width="match_parent"android:layout_height="match_parent“/> • Custom linksIntent test = new Intent(Intent.ACTION_VIEW, Uri.parse("foo.bar/data");if (test.resolveActivity(getPackageManager()) != null){ Pattern p = Pattern.compile("regular expression",Pattern.CASE_INSENSITIVE); Linkify.addLinks(text,p, "foo.bar/data" ); // Add specified link to matching text} • Note: Implementing a transform filter makes it possible to modify the text data before determining whether a matching activity exists or before launching such an activity when the link is clicked by a user

  31. Broadcasts Anonymous intent sent to receivers signalling an event occurred • Broadcasts can be either inter application or intra application • Priority values determine the order that broadcasts are received (higher priority first) • Permissions can be designated: Only receivers registering the appropriate permission receive notification • Sticky broadcasts persist the associated event data so activities can poll for the result of the most recent event without a receiver • It is possible to register and unregister receivers at points of an activity life cycle

  32. BroadCasts Custom name prefixed By the package • Registering receivers in XML <receiver android:name = ".MyClassName“ android:permission = "foo.bar.MY_PERMISSION"> <intent-filter android:priority="100"> <action android.name="foo.bar.action.ORDERED_BROADCAST" </intent-filter> </receiver> • Registering receivers in code private IntentFilter filter = new IntentFilter(action, dataType); Private MyReceiver = new MyReceiver(); @Override public void onResume() { registerReceiver(receiver, filter); } @Override public void onPause() { unregisterReceiver(receiver); } • To send broadcasts, use one of the methods: sendOrderedBroadcast, sendStickyBroadcast, or sendBroadcast Receivers extend BroadCastReceiver Receivers overriceonReceive method

  33. Sticky Broadcasts /** Check Battery state */ IntentFilter batIntentFilter = new intentFilter(Intent.ACTION_BATTERY_CHANGED); Intent battery = context.registerReceiver(null, batIntentFilter); // no launch int status = battery.getIntExtra(BatteryManager.EXTRA_STATUS, -1); // -1 default boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; /** Check network connectivity */ String svcName = Context.CONNECTIVITY_SERVICE; ConnectivityManager cm = (ConnectivityManager)context.getSystemService(svcName); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork.isConnectedOrConnecting(); boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;

  34. Pending Intents • Definition: An intent that is fired to an application at a time in the future • Launch: Occurs when some event occurs, like an alarm • Logic • Activities check if they are executing a pending intent (onCreate()) • A wrapper is stored around the pending intentPendingIntent.getActivity(activity, request, intent, flags); • Request codes reveal occurrences of the same pending intent. • Enough information is stored in the wrapping object to verify the security credentials at the time of invocation • Activities inherits permissions of the activity initiating the intent • Note: details covered in the chapter on notifications and widgets

More Related