1 / 36

Android – Advanced Topics

Android – Advanced Topics. Mobile Application Development Selected Topics – CPIT 490. Objective. Web Browsing Android Animation Android Backup Publishing Your Application. Web Browsing – Objectives.

siu
Télécharger la présentation

Android – Advanced Topics

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. Android – Advanced Topics Mobile Application Development Selected Topics – CPIT 490

  2. Objective • Web Browsing • Android Animation • Android Backup • Publishing Your Application

  3. Web Browsing – Objectives • Show how to launch the built-in Browser application in three ways. • Launch the browser to a specific URL. • Create text with links. • Launch a Google web search and specify the search criteria. • You will achieve these goals by creating and configuring the appropriate Intents within your application’s Activity class.

  4. Launch the Browser • Working with URIs: • Use Uri objects to identify the unique location of a piece of data. • Create a Uri object from a web URL using the parse() • Uri uriUrl = Uri.parse("http://www.google.com/"); • Creating the Intent: • Use android.content.Intent.ACTION_VIEW to view HTML • Specify the URI in the intent • Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); • Launching the Intent: • Call the startActivity() method, passing in your Intent • startActivity(launchBrowser);

  5. Text with Links • Another easy is simply by including links within text on the screen. • The TextView object can be configured to find these and turn them into clickable links • No special formatting commands or tags are needed within the string. • Example: • <TextView • android:layout_width="fill_parent" • android:layout_height="wrap_content" • android:text="@string/contains_links" • android:textSize="14dp" • android:autoLink="web" />

  6. Google Web Search • Enabling Web Searches • If content with a Google search, use web search Intent android.content.Intent.ACTION_WEB_SEARCH •  Intent search = new Intent(Intent.ACTION_WEB_SEARCH); • Supplying Search Criteria • UsesSearchManager.QUERY intent extra field for search criteria • Intent search = new Intent(Intent.ACTION_WEB_SEARCH); • search.putExtra(SearchManager.QUERY, "pygmy goats"); • startActivity(search);

  7. Becoming a Browser • For more fine control over web content, use theWebView control. • This special view allows fine control over rendering of web content. • In the following, we describe: • How you can embed an Android WebView in your application with theWebKit engine. • How to both load an external URL and render custom markup that you supply in-app.

  8. Becoming a Browser • Setting up the WebView Widget • Declare it in a layout file • Access it from an Activity and tell it what to do. • <?xml version="1.0" encoding="utf-8" ?> • <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" • android:orientation="vertical" • android:layout_width="fill_parent" • android:layout_height="fill_parent" • > • <WebViewandroid:id="@+id/web_engine" • android:layout_width="fill_parent" • android:layout_height="fill_parent" • /> • </LinearLayout>

  9. Becoming a Browser • Requesting Internet Permission • <uses-permissionandroid:name="android.permission.INTERNET" /> • Load a Web Page • In your main activity, add the following code into the onCreate(): • WebView engine = (WebView) • findViewById(R.id.web_engine); • engine.loadUrl("http://mobile.tutsplus.com");

  10. Becoming a Browser • Render Custom Markup • Replace the loadUrl() call with loadData(), which takes three arguments: String htmlData, String mimeType, String encoding • String data = "<html>" + "<body><h1>Yay, Mobiletuts+!</h1></body>" + "</html>"; • engine.loadData(data, "text/html", "UTF-8"); • Note • JavaScript should be enabled: engine.getSettings().setJavaScriptEnabled( true );

  11. Becoming a Browser • Extra features • reload() : Refreshes and re-renders the page. • goForward() : Goes one step forward in browser history. • goBack() : Goes one step back in browser history. • Use WebSettings class to define the features of the browser. • WebSettingswebSettings = webView.getSettings(); • setBlockNetworkImage() : Block network images to reduce the data loading using the method. • setDefaultFontSize() : Set font size of the displayed web content • Other methods: setSaveFormData(), setJavaScriptEnabled(), setSavePassword(), setSaveFormData(), setJavaScriptEnabled(), setSupportZoom()

  12. Android Backup – Overview • Users store a lot of data on different applications like notes, game data, application settings, address book entries, • All these data cannot be recovered after they are gone. • Backup service hosted by Google was introduced in Android 2.2. • All the application data can use the backup service to store any data to the cloud.

  13. Creating a Backup of Runtime Data • Use BackupManager class to notify the Backup service to do backup and restore operations. • After the notification is received, the backup manager requests backup data from the application and delivers it to a cloud storage server during backup. • It also retrieves backup data from the backup transport and returns it to applications during a restore process. • A backup agent is the interface where the BackupManager communicates with the applications. • Extend the BackupAgent in their class. • Two methods need to be overridden: • onBackup() : triggered whenever there is a dataChanged() method call. • onRestore(): triggered whenever there is a requestRestore()

  14. Creating a Backup of Runtime Data • onBackup() has three parameters: • oldState—Return the state from the last backup. • data—The data that is backed up • newState—Write the current state of the backup, which becomes the oldState for the next backup • onRestore() has three parameters: • data—The data from the last backup. • appVersionCode—The application’s version code during the backup operation. The version code is defined as the attribute android:versionCode in the Android-Manifest XML file. • newState—Write the current state as the restore point.

  15. Creating a Backup of Runtime Data • public class MyBackupAgent extends BackupAgent { • @Override • public void onCreate() { • ... • } • @Override • public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState){ • ... • } • @Override • public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState){ • ... • } }

  16. Backing Up Files to the Cloud • BackupAgent is intended to save application run-time data. • BackupAgentHelper is intended to save files • Wrapper class for the backup agent class. • Supports two different kinds of backup helpers • SharedPreferencesBackupHelper to backup SharedPreferences files • FileBackupHelper to backup file

  17. Triggering Backup and Restore • To define Backup agent, add android:backupAgent attribute inside the application manifest file • <application android:label="Backup/Restore" android:backupAgent="myBackupAgent"> • Anytime the application triggers a backup or restore to the BackupManager, it initiates with the identified backup agent. • public class MyBandRActivity extends Activity { • BackupManager mBackupManager; • @Override • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); • ... • mBackupManager = new BackupManager(this); } • void dataUpdate() { ... • // We also need to perform an initial backup; ask for one • mBackupManager.dataChanged(); //use BackupAgent defined in manifest file • } }

  18. Triggering Backup and Restore • Use requestRestore() of the BackupManager to trigger restore. • triggers a call to the backup agent’s onRestore() method • Also, a factory data reset or when the application is reinstalled trigger restore for the application. • Android provides a command-line script bmgr that can trigger backup/restore • Back trigger: “ > adb shell bmgr backup <package> ” • Restore trigger: “ > adb shell bmgr restore <package> ” • To force the BackupManager to do the backup right away: “ > adb shell bmgr run ”

  19. Android Animation • Two types of animation: frame-by-frame and Tween animation. • Frame-by-frame animation needs an animation-list element in the layout file • Containing a list of item elements specifying an ordered list of the different pictures to display. • oneshot attribute specifies whether the animation is played only once or repeatedly • Example: res/anim/animated.xml • <?xml version="1.0" encoding="utf-8"?> • <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false"> • <item android:drawable="@drawable/anddev1" android:duration="200" /> • <item android:drawable="@drawable/anddev2" android:duration="200" /> • <item android:drawable="@drawable/anddev3" android:duration="200" /> • </animation-list>

  20. Android Animation • To display the frame-by-frame animation, • set the animation to a view’s background • a drawable can be retrieved by calling getBackground() and casting it to AnimationDrawable • calling the start() method starts the animation. • ImageViewim = (ImageView) this.findViewById(R.id.myanimated); • im.setBackgroundResource(R.anim.animated); • AnimationDrawable ad = (AnimationDrawable)im.getBackground(); • ad.start();

  21. Android Animation • Tween animation uses a different approach that creates an animation by performing a series of transformations on a single image. • Android provides access to the following classes that are the basis for all the animations • AlphaAnimation—Controls transparency changes • RotateAnimation—Controls rotations • ScaleAnimation—Controls growing or shrinking • TranslateAnimation—Controls position changes • Used for transitions between activities, layouts, views, etc. • Defined in the layout XML file as <alpha>, <rotate>, <scale>, and <translate>.

  22. Example • Creates a new mail animation that can be used when mail is received. • Layout file: res/layout/main.xml • <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" • android:orientation="vertical" android:layout_width="fill_parent" • android:layout_height="fill_parent" • android:gravity="center" > • <ImageView android:id="@+id/myanimated" • android:layout_width="wrap_content" • android:layout_height="wrap_content“ • android:src="@drawable/mail" /> • <Button • android:id="@+id/startAnimated" • android:layout_width="wrap_content" • android:layout_height="wrap_content" • android:text="you’ve got mail" /> • </LinearLayout>

  23. Example • Animation file: res/anim/animated.xml • <?xml version="1.0" encoding="utf-8"?> • <set xmlns:android="http://schemas.android.com/apk/res/android" • android:interpolator="@android:anim/accelerate_interpolator"> • <translate android:fromXDelta="100%p" android:toXDelta="0“ android:duration="5000" /> • <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="3000" /> • <rotate android:fromDegrees="0“ android:toDegrees="-45" • android:toYScale="0.0“ android:pivotX="50%" • android:pivotY="50%“ android:startOffset="700" • android:duration="3000" /> • <scale android:fromXScale="0.0“ android:toXScale="1.4" • android:fromYScale="0.0“ android:toYScale="1.0" • android:pivotX="50%“ android:pivotY="50%" • android:startOffset="700“ android:duration="3000" • android:fillBefore="false" /> </set>

  24. Example • Main Activitiy • package edu.odu.cs.cs495.animation; • import android.app.Activity; import android.os.Bundle; • import android.view.View; import android.view.View.OnClickListener; • import android.view.animation.Animation; • import android.view.animation.AnimationUtils; • import android.widget.Button; import android.widget.ImageView; • public class myanimation extends Activity { /** Called when the activity is first created. */ • @Override • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); setContentView(R.layout.main); • final ImageView im = (ImageView) this.findViewById(R.id.myanimated); • final Animation an = AnimationUtils.loadAnimation(this, R.anim.animated); • im.setVisibility(View.INVISIBLE); • Button bt = (Button) this.findViewById(R.id.startAnimated); • bt.setOnClickListener(new OnClickListener(){ • public void onClick(View view){ im.setVisibility(View.VISIBLE); • im.startAnimation(an); } }); } }

  25. Publish to Android Market • The Checklist • Have I tested my application extensively? • Emulator + Physical device • Multiple hardware devices running different Android versions. • Does my application perform well? • Performance is really important especially in games • Have I decided on SDK compatibility? • Android 2.2 & 2.3 dominate?

  26. Publish to Android Market • Publishing an application requires these: • Export your application as an APK (Android Package) file. • Generate your own self-signed certificate and digitally sign your application with it. • Deploy the signed application. • Use the Android Market for hosting and selling your application.

  27. Getting your application ready • Step 1: Request necessary Android permissions • Make sure that you’re requesting all necessary permissions, otherwise your application won’t work. • <uses-permissionandroid:name="android.permission.VIBRATE" /> • <uses-permissionandroid:name="android.permission.INTERNET" /> • <uses-permissionandroid:name="android.permission.REBOOT" /> • Step 2: Specify a name (label) and icon • Name your application and give it an icon using the android:label and android:icon attribute in the application tag • <applicationandroid:label="@string/app_name" android:icon="@drawable/myIcon" > • This name is displayed in the Settings ➪ Apps section of your Android device

  28. Getting your application ready • Step 3: Configure version manifest data • Pick a version your application using android:versionCode and android:versionName. • versionCode is an integer that must increment for every update. Not used by android system but used by developer’s to obtain the application’s version number. Used by android market to find whether a new version exist or not. versionCode can be retrieved programmatically using getPackageInfo() method from the PackageManagerclass • PackageManager pm = getPackageManager(); • PackageInfopi = pm.getPackageInfo(“net.learn2develop.LBS”, 0); • Toast.makeText(getBaseContext(), “VersionCode: ” + Integer.toString(pi.versionCode), Toast.LENGTH_SHORT).show(); • versionName is a user-friendly value (e.g., 0.1 or 1.0b or 2.4.1). It is visible to the users • <manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.example" android:versionCode="1" android:versionName="1.0.0" >

  29. Getting your application ready • Step 4: Set compatibility options • If you’re utilizing Android features that aren’t available in older versions specify a set of version requirements within uses-sdk. • android:minSdkVersion The minimum Android platform API level on which your application will be able to run. • android:targetSdkVersion The API level that your application was designed to run on. • android:maxSdkVersion An upper limit for compatibility. Don’t set this unless you have a very good reason to. • Step 5: Cleanup files and remove logging

  30. Getting your application ready • Step 6: Sign and ZIP-align your application • Android applications must be digitally signed with a certificate that the developer holds to ensure the authenticity. • Pick a strong password for your private key and ensure to keep it safe • Eclipse by default signs compiled apps with debug key. • Use Export Wizard: • 1.Select the project and select File > Export. • 2.Open the Android drop-down and select Export Android Application • 3.Follow the wizard’s steps to compile, sign and ZIP-align your application. Your validity period must extend 2033 or else the Android Market will reject your app! Create a new one for the first time or use an existing one

  31. Getting your application ready • In Eclipse, pressing F11 will automatically deploy the application in the Emulator. You can verify this by going to Windows ➪Preferences in Eclipse, expanding the Android item, and selecting Build. Eclipse uses a default debug keystore (appropriately named “debug.keystore”) to sign your application. A keystore is commonly known as a digital certificate • Debug certificate cannot be used to publish your application. Manually you could generate your certificate using keytool. Eclipse has a wizard to make this process easier • Select the project, File ➪ Export. . . . In the Export dialog, expand the Android item and select Export Android Application. Click Next. The project should now be displayed. Click Next. Select the “Create new keystore” option to create a new certificate (keystore) for signing your application. Enter a path to save your new keystore and then enter a password to protect the keystore. Click Next. Provide an alias for the private key and enter a password to protect the private key. You also need to enter a validity period for the key. Finally, enter your name in the field labeled First and Last Name. Click Next. Enter a path to store the destination APK file.Click Finish. The APK file will now be generated

  32. Getting your application ready • If your application uses Google Maps API: • As your MD5 certificate is new now, you need to get Google Maps API key with this MD5 certificate, if your code uses Google API • C:\Program Files\Java\jre6\bin>keytool.exe -list -v -alias DistributionKeyStoreAlias -keystore “C:\Users\username\Desktop\MyNewCert.keystore” -storepass keystorepassword -keypass keypassword –v • Add the Google Maps API key in main.xml • <com.google.android.maps.MapView … android:apiKey=”your_key_here” /> • Export the application again as mentioned in previous slide using the existing key • For applications that use the Maps API key, note that the Maps API key must be associated with the new keystore that you use to sign your APK file

  33. Getting your application ready • Install using adb (Android Debug Bridge) • adb.exe is located at platform-tools folder of the Android SDK • adb install “C:\Users\username\Desktop\LBS.apk” • List the devices connected: adb devices • To install on a specific device: adb –s emulator-5556 install LBS.apk • emulator-5556 was retrieved as a result of the command adb devices • You could also deploy an application using DDMS by choosing /data/app folder and use the “Push a file onto the device” button • Uninstall an application: adb uninstall packagename.applicationname

  34. Becoming a Market Publisher • Requirements: • APK should be the file format available • Two screenshots (DDMS can be used to get picture of running application on a device or emulator) • You need to provide a high-resolution application icon. This size of this image must be 512x512 pixels. • Registration • 1. Register as a publisher and setup your profile. • http://market.android.com/publish/Home and sign in with your Google account • Fill out all the required information along with your real phone number • Note: you can always change “developer name” later via your profile page • 2. Read and agree to the Android Market Developer Distribution Agreement. • http://www.android.com/us/developer-distribution-agreement.html • http://www.android.com/market/terms/developer-content-policy.html • 3. Pay a registration fee of $25 USD via Google Checkout. • Click the Google Checkout button and pay the one-time registration fee

  35. Becoming a Market Publisher • Uploading an application • Login to your publisher account and click “Upload an Application”. • Fill in all of the form data and include screenshots if you can and provide a precise, short and well-formatted description. • You can also choose whether or not you want to release it as a free or paid app. • Click “Publish.” • Congratulations, you’ve just successfully published an application to the Android Market!

  36. References • App Development for Smart Devices • http://www.cs.odu.edu/~cs495/

More Related