Android 101: How to draw on a SurfaceView and handle touch events. Richard A. Perez Android 101

Size: px
Start display at page:

Download "Android 101: How to draw on a SurfaceView and handle touch events. Richard A. Perez Android 101"

Transcription

1 Android 101: How to draw on a SurfaceView and handle touch events. Richard A. Perez Android 101

2 Table of Contents Introduction... 3 Android Manifest... 4 Package... 4 Version... 4 Uses SDK... 4 Declare starting activity... 5 Resources... 5 Drawable... 5 Layout... 5 Menu... 6 Values... 6 Anim... 7 Main Activity... 8 OnCreate... 8 OnCreateOptionsMenu... 8 OnOptionsItemSelected... 8 OnResume... 9 Drawing Surface IncomingHandlerCallback Constructor SurfaceCreated SurfaceChanged SurfaceDestroyed Draw UpdatePhysics OnTouchEvent SetTextView OnWindowFocusChanged MenuRestart OnResume... 13

3 OnPause Target Thread mrun mmode Run SetState Targeting Targeting Class The Factory Pattern Draw MyRect SurfaceChanged OnTouch UpdatePhysics InitMyRects MenuRestart Testing Touch Import Git Attribution... 23

4 Introduction This document is intended for developer s who have some experience in setting up a development environment and are familiar on an introductory level with the Java programming language. I have created a project and commented the classes, methods and member groupings in hopes it will simplify the learning of Android and its lifecycle events. I have tried to include as many best practices encouraged by Android as I can but you will need to read their official developer guide for a full understanding. Many applications fail when the Activity lifecycle isn t fully understood. I created a project for you as a sample of what Android can do with relatively little coding. It is a simple interactive application that I have developed that will show you how to start manipulating pixels on a canvas. Also, as well as drawing on the SurfaceView object I include details on how to handle touch events and include methods for providing accessibility for users with special needs. I also have setup a Github account, a source control management site, and am hosting code from there that will be useful when using these samples on your own. You should view or download the full source code that is found in this guide from this link. Throughout the document I ll add in shortcuts and hotkeys that are useful. If you still rely on your mouse, it s a good practice to start using and memorizing hotkeys to increase your productivity. The phrase Mouse Fatigue is real and you ll find that simply moving your hand from the keyboard to the mouse over and over will get more tiring over time than using hotkeys to move windows or opening and closing files and directories. Don t make programming any harder than it already is! After creating a new Android project a couple of folders of interest are src and res, here your source code and resources, such as bitmaps and sound files, are placed. The AndroidManifest.xml file is a declaration file for the starting Activity and permissions. The strings.xml in the values folder should be used for any strings, where the value will not change. There is also an ic_launcher_web.png file that can be used for the application icon in the developer console page when you are ready to make the app listing with Google. The guide itself is intended to be a complete overview of the sample project I have provided for you. I start with the AndroidManifest.xml file which declares the project package (unique id) and the versions of the Android SDK that will be required of the user s phone. The res or resources folder is where your images and icons are placed as well the layout, menu, and static strings.xml file. The src code sections contains all of our source code. The intermediate topic to this guide is the use the use of the Factory Pattern design pattern. I use this to create and return classes that will perform the updating of game physics, and drawing to the canvas. The logic of both, will change as the state of the application progresses. In this sample we have two implementations for each. One for the running state and one for the end state. We only need to use one of them at one time. The Factory pattern is useful for switching out these classes, dynamically if needed, based on the state of the application. Learning and using the Factory pattern will help keep your application extensible by executing different code implementations to methods that share identical signatures while separating the actual object creation from its usage.

5 Android Manifest The AndroidManifest.xml file is where the application package is declared and you can set permissions for the application to implement use of the internet, memory cards, and other features. Package The package here is touch.target. This declaration means that if this application were to be listed on the Google Play store today you would see touch.target at the end of the URL link on the homepage of the application. Also it s the unique identifier for the application and must be unique across the entire Google Play store listings. This is a little misleading though, as you don t actually need to have the package in your src. It s simply declared in the manifest. package="touch.target" Version Every APK (Android Application Package) you generate with the intention of having hosted on Google Play will need to have a version number tied to it. You will need to increment the version code and version name. Your APK s are stored in numerical fashion and will need to be numbered correctly in order to have the latest release the one on the storefront whether in alpha, beta or production. android:versioncode="1" android:versionname="1.0" Uses SDK Out of the box Android will suggest a minimum and a target SDK, but code to your needs to get the task done. If raising the minimum version is needed for an SDK API method call or object then you can traverse to the Android dashboard and see what percent the missing version has in the marketplace and decide if missing that percentage of the possible users is worth the code you are implementing or if it would be worth to find a different way to do the same task and keep the minsdkversion as low as possible. <uses-sdk android:minsdkversion="8" android:targetsdkversion="21" />

6 Declare starting activity Android can have multiple activities but one has to have the Main Intent filter declared inside of it so you can declare the starting Activity of the application. <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> Resources Drawable In the drawable folders, the ic_launcher.png icons are placed. These are the phone launch icons the user will see on their device. Using Eclipse you can edit icons in place if you want to, usually I open with windows viewer and open the image in Paint.net but you can of course edit however you like. You can create a drawable-nodpi for images to be used but not be scaled by Android on use. You can also create a new icon set at any time followin the steps on the right. Eclipse Create New Icon Set 1. Alt-F 2. New 3. Other 4. Android Icon Set Layout Default layout is the activity_main.xml layout file. Click onto activity_main.xml tab at the bottom of the IDE for the GUI create view. Here you can see all the controls you can add into an application and change the settings of them. You can click on the activity_main.xml tab near the bottom of the Eclipse IDE to see or edit the actual XML. You can start to add widgets to see the layout on your device you just won t have access to the functionality until you implement it. <?xml version="1.0" encoding="utf-8"?> <merge xmlns:android=" android:id="@+id/merge" android:layout_width="fill_parent" android:layout_height="fill_parent" > <touch.target.surface.drawingsurface android:id="@+id/drawing_surface" android:layout_width="fill_parent" android:layout_height="fill_parent" /> Once you have layout objects solidified such as buttons or text fields then the layout should be independent of the actual classes that implements the logic. This means you can then work on

7 perfecting the implementation and perfecting the layout separately the bonus being that you can have two people do it separately. <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerinparent="true" android:gravity="center_horizontal" android:textcolor="#000000" android:textsize="24sp" android:textstyle="italic" android:visibility="visible" /> </RelativeLayout> </merge> Menu You can declare your menu items in a menu.xml layout file like this. Declaring the id for handling on press, the icon for the item to have if the phone version supports it and the string reference to the title of the menu item. <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android=" > </menu> <item android:id="@+id/restart" android:icon="@drawable/ic_launcher" android:title="@string/restart"/> Values Commonly used in here is the strings.xml class, where you should store all your static strings whose value will not change throughout the course of the applications lifecycle.

8 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">touch Demo</string> <string name="message_text">tap Screen when boxes\nare overlapping</string> <string name="restart">restart?</string> </resources> Anim You can store your animation xml files in a folder titled anim here you store your xml files with the animations you will be using for view objects. Used modestly, animations can enhance an application with a splash screen or other visual cue to keep the user involved. Our project extends the SurfaceView class and that class extends view, this allows us to add animation to it. For the intro screen of this application, I take the TextView object that shows the title and start by the animation by expanding it and, then as it fades into view, collapses it to its regular size. I manipulate two effects here the scale effect, which is simply resizing of the image and the alpha for transparency. The fromxscale is the starting point, 2 is the starting location, and the toxscale is 1. This means that the view object will start out expanded and reduce to the normal view, we can set the pivot or the point of focus the view expands from in the pivotx and pivoty locations. Here it s centered so its 50% height and 50% width. <?xml version="1.0" encoding="utf-8"?> <set xmlns:android=" android:fillafter="true" > </set> <scale android:duration="900" android:fromxscale="2" android:fromyscale="2" android:interpolator="@android:anim/linear_interpolator" android:pivotx="50%" android:pivoty="50%" android:toxscale="1" android:toyscale="1" /> <alpha android:duration="900" android:fromalpha="0.0" android:interpolator="@android:anim/accelerate_interpolator" android:toalpha="1.0" />

9 The alpha effect is declared next and is a transparency effect. The duration is for how long in milliseconds the effect will run for. The alpha (transparency) transition is for a nice dissolve in effect. The interpolator is the style of the animation effect. In the scale I use a linear interpolator so it animates the view object at a constant rate. For the alpha I use the accelerate_interpolator, this makes the dissolve effect increase over time. Refer to the Animation documents in the official Android developer tutorials. Main Activity The Main Activity is the starting point for the coding in the application and it extends an Activity class meaning that the Android lifecycle calls will start here. OnCreate Uses setcontentview so you can instantiate your starting class objects and then reference its member s right after it returns to have access to UI objects protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // get reference to our surface drawingsurface = (DrawingSurface) findviewbyid(r.id.drawing_surface); drawingsurface.settextview((textview) findviewbyid(r.id.pause_message)); OnCreateOptionsMenu Here your options menu from an XML layout file is created. Also we can create the handler for menu option selections. public boolean oncreateoptionsmenu(menu menu) { super.oncreateoptionsmenu(menu); MenuInflater inflater = getmenuinflater(); inflater.inflate(r.menu.main, menu); return true; OnOptionsItemSelected Here you start the handling of the menu item selections. Using the item id marked in the menu xml file we can tell which menu button was pressed and execute code as we need to. public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case R.id.restart: drawingsurface.menurestart(); return true; default: return super.onoptionsitemselected(item);

10 OnResume On resume the application should have the view objects ready and can start animating the intro for a splash screen effect. We implement the Animation Listener so we can tell when starting and finishing animating the view for the user. protected void onresume() { super.onresume(); // start the application out by modifying the view and don't accept user // input until the animation ends Animation anim = AnimationUtils.loadAnimation(this, R.anim.intro); anim.reset(); anim.setanimationlistener(new AnimationListener() { public void onanimationstart(animation animation) { // if the animation isn't finished we shouldn't be drawing on it drawingsurface.introfinished = false; public void onanimationrepeat(animation animation) { // TODO Auto-generated method stub ); public void onanimationend(animation animation) { // this animation is longest and touch should be ready when this // completes drawingsurface.introfinished = true; Animation anim2 = AnimationUtils.loadAnimation(this, R.anim.warp_in); anim2.reset(); drawingsurface.clearanimation(); drawingsurface.startanimation(anim); drawingsurface.messagetextview.clearanimation(); drawingsurface.messagetextview.startanimation(anim2); drawingsurface.onresume();

11 Drawing Surface IncomingHandlerCallback Allows the application to show messages to the user for different states by setting text to a TextView object and showing or hiding this on the UI. The variables for the code to run are packed into the Message object using a Bundle object of values. class IncomingHandlerCallback implements Handler.Callback { /** * The Message object can contain more than one value. */ public boolean handlemessage(message m) { // handle message code messagetextview.setvisibility(m.getdata().getint("show")); messagetextview.settext(m.getdata().getstring("message")); return true; Constructor In the constructor we register the surfaceholder callback s and allow the application to perform actions related to creating and drawing on your drawing surface. We create a new Handler object to send messages or run code to update the UI. Finally, we create a new TargetThread, the state of this on resuming the application will determine whether to restart or start an entirely new thread. public DrawingSurface(Context con, AttributeSet attrs) { super(con, attrs); context = con; // register the call back interface SurfaceHolder holder = getholder(); holder.addcallback(this); // prepare the thread and its message handler (handlers can also execute // code if needed) myhandler = new Handler(new IncomingHandlerCallback()); targetthread = new TargetThread(getHolder(), con, myhandler, this); SurfaceCreated Surface created is called on start of the application and will start your thread if it s in the NEW state. If restarting the application the thread may be TERMINATED, in which case a new one is created and started. public void surfacecreated(surfaceholder holder) { if (targetthread.getstate() == Thread.State.TERMINATED) { targetthread = new TargetThread(holder, context, myhandler, this); targetthread.start(); targetthread.setrunning(true);

12 else if (targetthread.getstate() == Thread.State.NEW) { targetthread.start(); targetthread.setrunning(true); SurfaceChanged Logic is handled in the target class, there the storing of and usage of the screen size is performed. At this point the values reflect the screen size minus the status bar or UI objects using screen space, what is left is the actual pixels of the full screen that we can manipulate for our application. public void surfacechanged(surfaceholder holder, int format, int width, int height) { targeting.surfacechanged(holder, height, width); SurfaceDestroyed Execution of the running thread should be blocked when destroying the surface. public void surfacedestroyed(surfaceholder holder) { boolean retry = true; targetthread.setrunning(false); while (retry) { try { targetthread.join(); retry = false; catch (InterruptedException e) { Draw For this project, the targeting class will handle our draw methods. We use the screen height and width and draws things relative to the screen size to ensure a similar experience on all devices. public void draw(canvas canvas) { super.draw(canvas); targeting.draw(canvas); UpdatePhysics The targeting class handles the logic in updating physics. Depending on the state we may be in the running or the end state and the physics will change. public void updatephysics() { targeting.updatephysics(); OnTouchEvent Call performclick() if ACTION_UP this will allow for the accessibility methods to fire, which are needed for users that have special needs. Check for intro animation to have finished to accept user

13 input. Unpause thread and begin cycling the draw/update loop. On the next touch event the code should then start performing the logic of the targeting classes implementation. There is also the chance that the application is restarting and the thread needs to be created immediately on touch. public boolean performclick() { super.performclick(); return true; public boolean ontouchevent(motionevent event) { synchronized (targetthread.msurfaceholder) { // if restarting the thread may not be valid, surface created will // not be called to do this for us. if (recreatethread) { recreatethread = false; if (targetthread.getstate() == Thread.State.TERMINATED) { targetthread = new TargetThread(getHolder(), context, myhandler, this); targetthread.start(); targetthread.setrunning(true); else if (targetthread.getstate() == Thread.State.NEW) { targetthread.start(); targetthread.setrunning(true); if (event.getaction() == MotionEvent.ACTION_UP) { performclick(); /** * If the intro is finished we can perform actions on the touch * events. */ if (introfinished && touchready) switch (targetthread.mmode) { case TargetThread.STATE_PAUSE: targetthread.setstate(targetthread.state_running); break; case TargetThread.STATE_RUNNING: return targeting.ontouch(event); return super.ontouchevent(event); SetTextView Sets a TextView object reference that will display messages to the user. Depending on state it will be hidden or shown to the user. public void settextview(textview textview) { messagetextview = textview;

14 OnWindowFocusChanged When the SurfaceView View is in view and can accept user touch we can set a flag to let the touch listener know we are ready or done accepting user touch in this View. public void menurestart() { targeting.menurestart(); MenuRestart Handle s the user pressing menu options to restart the game, this method is called after the method declared to handle the menu selection in MainActivity is called. To easily find this out move the cursor over the method call menurestart() and press Control-Shift-G to see where in the code the method is being called from. The opposite is pressing F3 on a method call to go straight to the method code. public void onwindowfocuschanged(boolean haswindowfocus) { super.onwindowfocuschanged(haswindowfocus); if (haswindowfocus) { touchready = true; else { touchready = false; OnResume The targetthread should be newly created and ready to start but if the application is restarting this won t be the case. Create a flag so when the user touches the screen next the thread will begin. public void onresume() { if (targetthread.getstate() == Thread.State.TERMINATED) { recreatethread = true; OnPause If the target thread is running it should be paused and set the program execution path to be false so it won t run the thread. public void onpause() { if (targetthread!= null) { targetthread.pause(); targetthread.setrunning(false); Target Thread The Thread class is usually alive for shorter amounts of time than the Activity itself. If you use DDMS perspective in Eclipse you can see the Activities and Threads alive from other applications and their consumption of resources and the impact of your new activity on top of it.

15 mrun Used to tell if the application should be running the thread loop of update and draw. public boolean mrun = false; mmode Used to tell what state the application is in, and if to send messages from the UI. public int mmode; Run Here we will get a new canvas from the surface holder. If the application is running then the update physics method will be called as well as the draw method public void run() { while (mrun) { Canvas c = null; try { c = msurfaceholder.lockcanvas(null); if (c!= null) { synchronized (msurfaceholder) { if (mmode == STATE_RUNNING) drawingsurface.updatephysics(); drawingsurface.draw(c); finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c!= null) { msurfaceholder.unlockcanvasandpost(c); SetState Called on changing of the state of the targetthread. If you are changing the state to be running then you will call the handler and set the TextView object that is displaying the text to be hidden from the user. If setting the state of the thread to be paused then you can send a message via the Handler and make the TextView visible so the user knows the thread is paused. The Message object contains a set of data that is packed into the Bundle object. public void setstate(int mode, CharSequence message) { synchronized (msurfaceholder) { mmode = mode; Message msg; Bundle bundle; switch (mmode) {

16 case STATE_RUNNING: msg = mhandler.obtainmessage(); Bundle b = new Bundle(); b.putstring("message", ""); b.putint("show", View.INVISIBLE); msg.setdata(b); mhandler.sendmessage(msg); break; case STATE_PAUSE: Resources res = context.getresources(); CharSequence str = ""; str = res.gettext(r.string.message_text); if (message!= null) { str = message + "\n" + str; msg = mhandler.obtainmessage(); bundle = new Bundle(); bundle.putstring("message", str.tostring()); bundle.putint("show", View.VISIBLE); msg.setdata(bundle); mhandler.sendmessage(msg); break; Targeting Targeting Class The targeting class contains the inner class Target, this contains a Rect object that will provide the bounds of the objects on screen and determine if they are interacting each other or should be from a physics standpoint. Two objects use this class the homing object and the target object. To handle the drawing and physics updating I created Factory classes to return the specific classes that I am using at that application state s time. For this sample I have two methods, the draw() method and the updatephysics() method which both have a running and an end implementation. The Factory Pattern Using the Factory pattern you can switch out different implementations for the same task. Such as if you are playing a game with levels one level may have different speeds or settings for things such as background color. In this case we are switching between running and end states for our application. In creating a new Draw or UpdatePhysics class we start with using the running implementation but this will change on the end state and we will want to draw or update our end screen with the end implementation. The factories will create these objects of one type implementing a single interface. The method calls for draw() and updatephysics() are captured in a base interface and each class using that interface should have some differences in the implementation. In the sample project provided

17 we have two draw classes. They both have the draw() method implemented but the exact implementation is different. Draw The initial Draw class being used is the running implementation. Inside the DrawFactory a new Draw object is drawn based on the value of currentdraw. Drawing the target object, homing object and wallpaper background is handed to the Draw class created by the Factory. String currentdraw = "running"; Draw draw = DrawFactory.createDraw(currentDraw); public void draw(canvas canvas) { draw.draw(canvas, this); public class DrawRunningImpl implements Draw { public void draw(canvas canvas, Targeting targeting) { // draw based on targeting state before or after press if (!targeting.istouchtimingset) canvas.drawcolor(color.blue); else if (targeting.istouchedontime) canvas.drawcolor(color.green); else canvas.drawcolor(color.red); // draw on the canvas the two rectangle objects. canvas.drawrect(targeting.targetrect.rect, targeting.targetobjectpaint); canvas.drawrect(targeting.homingrect.rect, targeting.targethomingpaint); public class DrawEndImpl implements Draw { /** * the draw class must be called if its implementing Draw */ public void draw(canvas canvas, Targeting targeting) { canvas.drawcolor(color.yellow); You can see the DrawRunningImpl and DrawEndImpl only differ in that the end phase simply draws a yellow background. While running, the implementation still has decisions to make on wether the user has touched the screen yet and if the application has updated the applications since then. But they both use the same draw(canvas canvas, Targeting targeting) method signature. MyRect An inner class that is used to represent the target rectangle and the homing rectangle. public class MyRect {

18 /** * will be used to determine the draw pixels of the object. */ public Rect rect; /** * Create a new Rect when you create a new Target. */ public MyRect() { rect = new Rect(); public MyRect homingrect = new MyRect(); public MyRect targetrect = new MyRect(); SurfaceChanged After the screen s actual pixels are available to manipulate the method surfacechanged is called with the new height and width as parameters. SurfaceChanged is NOT called after onrestart(). public void surfacechanged(surfaceholder holder, int height, int width) { // called when the surface is created for the thread screenheight = height; screenwidth = width; // by scaling the starttargetpixel from the smallest side we can make // sure that the start target pixel is in a similar location on // different devices and closes in on itself. if (screenwidth <= screenheight) starttargetpixel = screenwidth / 20; else starttargetpixel = screenheight / 20; // place targets initmyrects(); OnTouch To register a valid touch the press has to be while the point is on the target location and is within the buffer range. We set a flag to let the updatephysics class know that it must handle the touch event and change the physics accordingly. So first we flag that there is a new touch event and next we have a flag so we make sure to check if it s on time or a miss. public boolean ontouch(motionevent event) { // touch tracks the life cycle of the touch event if (!isroundover &&!istouched) { if (event.getaction() == MotionEvent.ACTION_DOWN) { // touch event has happened istouched = true; istouchupdated = false; return false; return true;

19 UpdatePhysics Our Draw class works in tandem with the UpdatePhysics class to refresh and update the screen that is in front of the user. Using our Factory we can get the new draw method when we are in the end state. Our TargetThread makes calls to updatephysics only when the application is running. Otherwise, what we want the thread to do is draw the same screen until the game should be changing. String currentphysics = "running"; UpdatePhysics updatephysics = UpdatePhysicsFactory.createUpdatePhysics(currentPhysics); public void updatephysics() { updatephysics.updatephysics(this); // the moving homing rectangle has minimized completely if (updatephysics.getistobereset()) { currentphysics = "end"; updatephysics = UpdatePhysicsFactory.createUpdatePhysics(currentPhysics); currentdraw = "end"; draw = DrawFactory.createDraw(currentDraw); public void updatephysics(targeting targeting) { // handle user touch if (targeting.istouched &&!targeting.istouchupdated) { targeting.istouchupdated = true; targeting.istouched = false; // check for touch on time if (targeting.homingrect.rect.left > (targeting.targetrect.rect.left - targeting.stroke_width) && (targeting.homingrect.rect.left < targeting.targetrect.rect.left + targeting.stroke_width)) { targeting.istouchedontime = true; targeting.istouchtimingset = true; // reduce the home target for next round targeting.targetrect.rect.left += targeting.starttargetpixel; targeting.targetrect.rect.top += targeting.starttargetpixel; targeting.targetrect.rect.right -= targeting.starttargetpixel; targeting.targetrect.rect.bottom -= targeting.starttargetpixel; // register the current round to be over if (targeting.targetrect.rect.left > targeting.screenwidth / 2) { istobereset = true; else { // count as missed and end round

20 targeting.istouchedontime = false; targeting.istouchtimingset = true; targeting.isroundover = true; // expand the target to show it was off time targeting.targetrect.rect.left -= targeting.starttargetpixel; targeting.targetrect.rect.top -= targeting.starttargetpixel; targeting.targetrect.rect.right += targeting.starttargetpixel; targeting.targetrect.rect.bottom += targeting.starttargetpixel; // don't let it set it back further than the first visible step if (targeting.targetrect.rect.left <= 0) { targeting.targetrect.rect.left = targeting.starttargetpixel; targeting.targetrect.rect.top = targeting.starttargetpixel; targeting.targetrect.rect.right = targeting.screenwidth targeting.starttargetpixel; targeting.targetrect.rect.bottom = targeting.screenheight - targeting.starttargetpixel; // reduce square size of homing target targeting.homingrect.rect.left++; targeting.homingrect.rect.top++; targeting.homingrect.rect.right--; targeting.homingrect.rect.bottom--; // when the left meets the right or the top meets the bottom means the // round is over and user touch will be accepted if (targeting.homingrect.rect.left >= targeting.homingrect.rect.right targeting.homingrect.rect.top >= targeting.homingrect.rect.bottom) { targeting.istouched = false; targeting.istouchedontime = false; targeting.istouchtimingset = false; targeting.istouchupdated = false; targeting.isroundover = false; targeting.homingrect.rect.left = 0; targeting.homingrect.rect.right = targeting.screenwidth - 1; targeting.homingrect.rect.top = 0; targeting.homingrect.rect.bottom = targeting.screenheight;

21 InitMyRects Android uses X and Y coordinates to map the view in front of the user but the origin, the (0,0) coordinate is not at the center of the screen in Android. It s actually in the top left corner of the screen. We set the homingobject to be at this point and stretch all the way to the other side of the screen, but we have to take one pixel from the right side of the screen to make sure the right side of the target is visible the same is true for the bottom of the screen. Using the starttargetpixel we can set the homingtarget inside the surfaceview and take the difference away from all sides to center it and once again subtracting one from the right side of the screen and the bottom of the screen. private void initmyrects() { homingrect.rect.top = 0; homingrect.rect.left = 0; homingrect.rect.right = screenwidth - 1; homingrect.rect.bottom = screenheight - 1; targetrect.rect.top = starttargetpixel; targetrect.rect.left = starttargetpixel; targetrect.rect.right = screenwidth - starttargetpixel - 1; targetrect.rect.bottom = screenheight - starttargetpixel - 1; MenuRestart If the user has pressed the menu restart option we have to perform actions to set the application back to its original state. This means to reset the physics to be our original physics version, in this case running. Also we reset the draw and physics to be the initial running implementations. public void menurestart() { // reset our factory methods currentphysics = "running"; updatephysics = UpdatePhysicsFactory.createUpdatePhysics(currentPhysics); currentdraw = "running"; draw = DrawFactory.createDraw(currentDraw); // reset our MyRect objects initmyrects(); //reset our flags for the targeting class istouched = false; istouchedontime = false; istouchtimingset = false; istouchupdated = false; isroundover = false; Testing Touch 1. Create New click Other select Android Test Project 2. Name the project 3. Select touch demo project to be tested choose build or 4.4W

22 4. Click FinishCreate a new class in the new package a. Name it TouchTests b. Have it extend ActivityInstrumentationTestCase2<MainActivity> c. Be sure to import the package of the test class. d. I import all the classes via touch.demo.*; e. Hold an instance of the Activity f. Run the class file not the project as an Android JUnit test. package touch.target.test; import android.test.activityinstrumentationtestcase2; import touch.target.mainactivity; import touch.target.surface.targetthread; public class TouchTargetsTest extends ActivityInstrumentationTestCase2<MainActivity> { private MainActivity mainactivity; public TouchTargetsTest() { super(mainactivity.class); public TouchTargetsTest(Class<MainActivity> activityclass) { super(mainactivity.class); protected void setup() throws Exception { super.setup(); mainactivity = getactivity(); public void testactivitynotnull(){ assertnotnull(mainactivity); public void teststartstatepaused() { int mode = mainactivity.drawingsurface.targetthread.mmode; assertequals(mode, TargetThread.STATE_PAUSE); Import Git You can use Eclipse to import the TouchTarget Demo project if you like. It is hosted on Github and you can import it directly from the Eclipse IDE. 1. Open Eclipse 2. Alt-F import 3. Git

23 a. Project from Git b. Clone URI i. ii. No password or user name is needed with public repositories. c. From here you will need the appcompat_library for backwards compatibility. d. You can create a new project for SDK 5.0 and this should have the library built for you, or you can build it from the SDK by selecting Import, select Android, Existing Android Code Into Workspace and selecting from inside the SDK the directory /extras/android/support/v7/appcompat. e. The Project should build out and now you can set the Touch Demo project to use the library. f. Go to project name in Project Explorer g. Click Alt-Enter to h. Select Android i. In the bottom is the Library section i. Remove the invalid library link ii. Click Add and select the appcompat support library v7 j. Now you can clean and build without errors. k. Once this is done you can plug in your device. l. Finally select Run as Android Application.

24 Attribution DISCLAIMER: The sample code described herein is provided on an "as is" basis, without warranty of any kind, to the fullest extent permitted by law. MobileApplications009 does not warrant or guarantee the individual success developers may have in implementing the sample code on their development platforms or in using their own IDE, all samples were developed in Eclipse Luna 4.4. MobileApplications009 does not warrant, guarantee or make any representations regarding the use, results of use, accuracy, timeliness or completeness of any data or information relating to the sample code. MobileApplications009 disclaims all warranties, express or implied, and in particular, disclaims all warranties of merchantability, fitness for a particular purpose, and warranties related to the code, or any service or software related thereto. MobileApplications009 shall not be liable for any direct, indirect or consequential damages or costs of any type arising out of any action taken by you or others related to the sample code. Android, Google and Google Play are trademarks of Google Inc. Portions of this pdf are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. Portions of this pdf are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. Eclipse and Eclipse Ready are trademarks of Eclipse Foundation, Inc. Thanks very much, Richard A. Perez MobileApplications009 Mobileapplications009@gmail.com

Programming of Mobile Services, Spring 2012

Programming of Mobile Services, Spring 2012 Programming of Mobile Services, Spring 2012 HI1017 Lecturer: Anders Lindström, anders.lindstrom@sth.kth.se Lecture 6 Today s topics Android graphics - Views, Canvas, Drawables, Paint - Double buffering,

More information

INTRODUCTION TO ANDROID

INTRODUCTION TO ANDROID INTRODUCTION TO ANDROID 1 Niv Voskoboynik Ben-Gurion University Electrical and Computer Engineering Advanced computer lab 2015 2 Contents Introduction Prior learning Download and install Thread Android

More information

GATAV 5. Animations Using a Game Loop

GATAV 5. Animations Using a Game Loop GATAV 5. Animations Using a Game Loop TOC 1. The basic principle. 2. Creating bubbles. 3. Making the bubbles more look alive. 4. The appearent look. 5. Making the audiance impressed. 6. Now it up to you:

More information

ANDROID (4) 2D Graphics and Animation, Handling Screen Rotation. Marek Piasecki

ANDROID (4) 2D Graphics and Animation, Handling Screen Rotation. Marek Piasecki ANDROID (4) 2D Graphics and Animation, Handling Screen Rotation Marek Piasecki Outline 2D graphics drawing Color / Paint / Canvas XML drawable (from resources) direct to a Canvas / View.onDraw() 2D animation

More information

LifeStreet Media Android Publisher SDK Integration Guide

LifeStreet Media Android Publisher SDK Integration Guide LifeStreet Media Android Publisher SDK Integration Guide Version 1.12.0 Copyright 2015 Lifestreet Corporation Contents Introduction... 3 Downloading the SDK... 3 Choose type of SDK... 3 Adding the LSM

More information

Solving an Android Threading Problem

Solving an Android Threading Problem Home Java News Brief Archive OCI Educational Services Solving an Android Threading Problem Introduction by Eric M. Burke, Principal Software Engineer Object Computing, Inc. (OCI) By now, you probably know

More information

Android Application Development. By : Shibaji Debnath

Android Application Development. By : Shibaji Debnath Android Application Development By : Shibaji Debnath About Me I have over 10 years experience in IT Industry. I have started my career as Java Software Developer. I worked in various multinational company.

More information

Mobila applikationer och trådlösa nät, HI1033, HT2013

Mobila applikationer och trådlösa nät, HI1033, HT2013 Mobila applikationer och trådlösa nät, HI1033, HT2013 Today: - User Interface basics - View components - Event driven applications and callbacks - Menu and Context Menu - ListView and Adapters - Android

More information

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ] s@lm@n Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ] Android AND-401 : Practice Test Question No : 1 Which of the following is required to allow the Android

More information

Android Application Model I

Android Application Model I Android Application Model I CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Rajiv Ramnath Reading: Big Nerd Ranch Guide, Chapters 3, 5 (Activities);

More information

App Development for Smart Devices. Lec #18: Advanced Topics

App Development for Smart Devices. Lec #18: Advanced Topics App Development for Smart Devices CS 495/595 - Fall 2011 Lec #18: Advanced Topics Tamer Nadeem Dept. of Computer Science Objective Web Browsing Android Animation Android Backup Presentation - Developing

More information

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Android Application Model I CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Rajiv Ramnath 1 Framework Support (e.g. Android) 2 Framework Capabilities

More information

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) Lecture 3: Android Life Cycle and Permission Entire Lifetime An activity begins its lifecycle when entering the oncreate() state If not interrupted

More information

Multiple devices. Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers

Multiple devices. Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers Multiple devices Multiple devices Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers Create a new directory in your project's res/ and name it using the

More information

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) Lecture 3: Android Life Cycle and Permission Android Lifecycle An activity begins its lifecycle when entering the oncreate() state If not

More information

EMBEDDED SYSTEMS PROGRAMMING Application Basics

EMBEDDED SYSTEMS PROGRAMMING Application Basics EMBEDDED SYSTEMS PROGRAMMING 2015-16 Application Basics APPLICATIONS Application components (e.g., UI elements) are objects instantiated from the platform s frameworks Applications are event driven ( there

More information

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed.

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed. Action Bar Introduction The Action Bar is a widget that is shown on top of the screen. It includes the application logo on its left side together with items available from the options menu on the right.

More information

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2.

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2. Outline 1. Set up Android Studio Android development Tiberiu Vilcu Prepared for EECS 411 Sugih Jamin 15 September 2017 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code

More information

Lab 1: Getting Started With Android Programming

Lab 1: Getting Started With Android Programming Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Eng. Jehad Aldahdooh Mobile Computing Android Lab Lab 1: Getting Started With Android Programming To create a new Android Project

More information

Meniu. Create a project:

Meniu. Create a project: Meniu Create a project: Project name: P0131_MenuSimple Build Target: Android 2.3.3 Application name: MenuSimple Package name: ru.startandroid.develop.menusimple Create Activity: MainActivity Open MainActivity.java.

More information

Android Programs Day 5

Android Programs Day 5 Android Programs Day 5 //Android Program to demonstrate the working of Options Menu. 1. Create a New Project. 2. Write the necessary codes in the MainActivity.java to create OptionMenu. 3. Add the oncreateoptionsmenu()

More information

1 카메라 1.1 제어절차 1.2 관련주요메서드 1.3 제작철차 서피스뷰를생성하고이를제어하는서피스홀더객체를참조해야함. 매니페스트에퍼미션을지정해야한다.

1 카메라 1.1 제어절차 1.2 관련주요메서드 1.3 제작철차 서피스뷰를생성하고이를제어하는서피스홀더객체를참조해야함. 매니페스트에퍼미션을지정해야한다. 1 카메라 1.1 제어절차 서피스뷰를생성하고이를제어하는서피스홀더객체를참조해야함. 매니페스트에퍼미션을지정해야한다. 1.2 관련주요메서드 setpreviewdisplay() : startpreview() : stoppreview(); onpicturetaken() : 사진을찍을때자동으로호출되며캡처한이미지가전달됨 1.3 제작철차 Step 1 프로젝트를생성한후매니페스트에퍼미션들을설정한다.

More information

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Diving into Android. By Jeroen Tietema. Jeroen Tietema, Diving into Android By Jeroen Tietema Jeroen Tietema, 2015 1 Requirements 4 Android SDK 1 4 Android Studio (or your IDE / editor of choice) 4 Emulator (Genymotion) or a real device. 1 See https://developer.android.com

More information

Our First Android Application

Our First Android Application Mobile Application Development Lecture 04 Imran Ihsan Our First Android Application Even though the HelloWorld program is trivial in introduces a wealth of new ideas the framework, activities, manifest,

More information

Mobile Application (Design and) Development

Mobile Application (Design and) Development Mobile Application (Design and) Development 7 th class Prof. Stephen Intille s.intille@neu.edu Northeastern University 1 Q&A Workspace setup in lab. Anyone try it? Anyone looking for a partner? Boggle

More information

Building MyFirstApp Android Application Step by Step. Sang Shin Learn with Passion!

Building MyFirstApp Android Application Step by Step. Sang Shin   Learn with Passion! Building MyFirstApp Android Application Step by Step. Sang Shin www.javapassion.com Learn with Passion! 1 Disclaimer Portions of this presentation are modifications based on work created and shared by

More information

05. RecyclerView and Styles

05. RecyclerView and Styles 05. RecyclerView and Styles 08.03.2018 1 Agenda Intents Creating Lists with RecyclerView Creating Cards with CardView Application Bar Menu Styles and Themes 2 Intents 3 What is Intent? An Intent is an

More information

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology Android App Development Mr. Michaud ICE Programs Georgia Institute of Technology Android Operating System Created by Android, Inc. Bought by Google in 2005. First Android Device released in 2008 Based

More information

Android HelloWorld - Example. Tushar B. Kute,

Android HelloWorld - Example. Tushar B. Kute, Android HelloWorld - Example Tushar B. Kute, http://tusharkute.com Anatomy of Android Application Anatomy of Android Application Java This contains the.java source files for your project. By default, it

More information

Introduction to Mobile Application Development Using Android Week Four Video Lectures

Introduction to Mobile Application Development Using Android Week Four Video Lectures Introduction to Mobile Application Development Using Android Week Four Video Lectures Week Four: Lecture 1: Unit 1: Multimedia Multimedia Support in Android Multimedia Support in Android We are now going

More information

LECTURE NOTES OF APPLICATION ACTIVITIES

LECTURE NOTES OF APPLICATION ACTIVITIES Department of Information Networks The University of Babylon LECTURE NOTES OF APPLICATION ACTIVITIES By College of Information Technology, University of Babylon, Iraq Samaher@inet.uobabylon.edu.iq The

More information

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering Getting Started Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador 1 Goals Setting up your development environment Android Framework

More information

Configuring the Android Manifest File

Configuring the Android Manifest File Configuring the Android Manifest File Author : userone What You ll Learn in This Hour:. Exploring the Android manifest file. Configuring basic application settings. Defining activities. Managing application

More information

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml Android Application Written in Java (it s possible to write native code) Good

More information

UNDERSTANDING ACTIVITIES

UNDERSTANDING ACTIVITIES Activities Activity is a window that contains the user interface of your application. An Android activity is both a unit of user interaction - typically filling the whole screen of an Android mobile device

More information

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices. Group B: Assignment No 8 Regularity (2) Performance(5) Oral(3) Total (10) Dated Sign Title of Assignment: To verify the operating system name and version of Mobile devices. Problem Definition: Write a

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi View System A system for organizing GUI Screen = tree of views. View = rectangular shape on the screen that knows how to draw itself wrt to the containing

More information

Mobila applikationer och trådlösa nät, HI1033, HT2012

Mobila applikationer och trådlösa nät, HI1033, HT2012 Mobila applikationer och trådlösa nät, HI1033, HT2012 Today: - User Interface basics - View components - Event driven applications and callbacks - Menu and Context Menu - ListView and Adapters - Android

More information

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings. Hello World Lab Objectives: Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.xml What to Turn in: The lab evaluation

More information

Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento

Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento Let s work with the listener Button button = ; button.setonclicklistener(new.onclicklistener() { public void

More information

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen Gill Cleeren Agenda Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen Lists and navigation Navigating from master to detail Optimizing the application Preparing

More information

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard.

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard. 44 CHAPTER 2 Android s development environment Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard. TIP You ll want the package name of your applications to be unique

More information

1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation

1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation 1. Location Services 1.1 GPS Location 1. Create the Android application with the following attributes. Application Name: MyLocation Project Name: Package Name: MyLocation com.example.mylocation 2. Put

More information

App Development for Smart Devices. Lec #9: Advanced Topics

App Development for Smart Devices. Lec #9: Advanced Topics App Development for Smart Devices CS 495/595 - Fall 2013 Lec #9: Advanced Topics Tamer Nadeem Dept. of Computer Science Objective Web Browsing Android Animation Android Backup Publishing Your Application

More information

Vienos veiklos būsena. Theory

Vienos veiklos būsena. Theory Vienos veiklos būsena Theory While application is running, we create new Activities and close old ones, hide the application and open it again and so on, and Activity can process all these events. It is

More information

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters Mobile Programming Lecture 5 Composite Views, Activities, Intents and Filters Lecture 4 Review How do you get the value of a string in the strings.xml file? What are the steps to populate a Spinner or

More information

Have a development environment in 256 or 255 Be familiar with the application lifecycle

Have a development environment in 256 or 255 Be familiar with the application lifecycle Upcoming Assignments Readings: Chapter 4 by today Horizontal Prototype due Friday, January 22 Quiz 2 today at 2:40pm Lab Quiz next Friday during lecture time (2:10-3pm) Have a development environment in

More information

EMBEDDED SYSTEMS PROGRAMMING UI and Android

EMBEDDED SYSTEMS PROGRAMMING UI and Android EMBEDDED SYSTEMS PROGRAMMING 2016-17 UI and Android STANDARD GESTURES (1/2) UI classes inheriting from View allow to set listeners that respond to basic gestures. Listeners are defined by suitable interfaces.

More information

Upon completion of the second part of the lab the students will have:

Upon completion of the second part of the lab the students will have: ETSN05, Fall 2017, Version 2.0 Software Development of Large Systems Lab 2 1. INTRODUCTION The goal of lab 2 is to introduce students to the basics of Android development and help them to create a starting

More information

Notification mechanism

Notification mechanism Notification mechanism Adaptation of materials: dr Tomasz Xięski. Based on presentations made available by Victor Matos, Cleveland State University. Portions of this page are reproduced from work created

More information

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Activity Basics Manifest File AndroidManifest.xml Central configuration of Android application Defines: Name of application Icon for

More information

Lab 3. Accessing GSM Functions on an Android Smartphone

Lab 3. Accessing GSM Functions on an Android Smartphone Lab 3 Accessing GSM Functions on an Android Smartphone 1 Lab Overview 1.1 Goals The objective of this practical exercise is to create an application for a smartphone with the Android mobile operating system,

More information

Embedded Systems Programming - PA8001

Embedded Systems Programming - PA8001 Embedded Systems Programming - PA8001 http://goo.gl/ydeczu Lecture 9 Mohammad Mousavi m.r.mousavi@hh.se Center for Research on Embedded Systems School of Information Science, Computer and Electrical Engineering

More information

CS 4330/5390: Mobile Application Development Exam 1

CS 4330/5390: Mobile Application Development Exam 1 1 Spring 2017 (Thursday, March 9) Name: CS 4330/5390: Mobile Application Development Exam 1 This test has 8 questions and pages numbered 1 through 7. Reminders This test is closed-notes and closed-book.

More information

Minds-on: Android. Session 2

Minds-on: Android. Session 2 Minds-on: Android Session 2 Paulo Baltarejo Sousa Instituto Superior de Engenharia do Porto 2016 Outline Activities UI Events Intents Practice Assignment 1 / 33 2 / 33 Activities Activity An activity provides

More information

Q.1 Explain the dialog and also explain the Demonstrate working dialog in android.

Q.1 Explain the dialog and also explain the Demonstrate working dialog in android. Q.1 Explain the dialog and also explain the Demonstrate working dialog in android. - A dialog is a small window that prompts the user to make a decision or enter additional information. - A dialog does

More information

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface? MOBILE COMPUTING CSE 40814/60814 Fall 2015 How many of you have implemented a command-line user interface? 1 How many of you have implemented a graphical user interface? HTML/CSS Java Swing.NET Framework

More information

COSC 3P97 Mobile Computing

COSC 3P97 Mobile Computing COSC 3P97 Mobile Computing Mobile Computing 1.1 COSC 3P97 Prerequisites COSC 2P13, 3P32 Staff instructor: Me! teaching assistant: Steve Tkachuk Lectures (MCD205) Web COSC: http://www.cosc.brocku.ca/ COSC

More information

Android Beginners Workshop

Android Beginners Workshop Android Beginners Workshop at the M O B IL E M O N D AY m 2 d 2 D E V E L O P E R D A Y February, 23 th 2010 Sven Woltmann, AndroidPIT Sven Woltmann Studied Computer Science at the TU Ilmenau, 1994-1999

More information

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle CS378 -Mobile Computing Anatomy of and Android App and the App Lifecycle Hello Android Tutorial http://developer.android.com/resources/tutorials/hello-world.html Important Files src/helloandroid.java Activity

More information

Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial

Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial Revision history 90001431-13 Revision Date Description A October 2014 Original release. B October 2017 Rebranded the document. Edited the document.

More information

Android Basics. Android UI Architecture. Android UI 1

Android Basics. Android UI Architecture. Android UI 1 Android Basics Android UI Architecture Android UI 1 Android Design Constraints Limited resources like memory, processing, battery à Android stops your app when not in use Primarily touch interaction à

More information

Applications. Marco Ronchetti Università degli Studi di Trento

Applications. Marco Ronchetti Università degli Studi di Trento Applications Marco Ronchetti Università degli Studi di Trento Android Applications An Android application typically consists of one or more related, loosely bound activities for the user to interact with.

More information

Embedded Systems Programming - PA8001

Embedded Systems Programming - PA8001 Embedded Systems Programming - PA8001 http://goo.gl/ydeczu Lecture 8 Mohammad Mousavi m.r.mousavi@hh.se Center for Research on Embedded Systems School of Information Science, Computer and Electrical Engineering

More information

Real-Time Embedded Systems

Real-Time Embedded Systems Real-Time Embedded Systems DT8025, Fall 2016 http://goo.gl/azfc9l Lecture 8 Masoumeh Taromirad m.taromirad@hh.se Center for Research on Embedded Systems School of Information Technology 1 / 51 Smart phones

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Teodoro Montanaro Politecnico di Torino, 2016/2017 Disclaimer This is only a fast introduction: It is not complete (only scrapes the surface) Only superficial

More information

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING This document can be downloaded from www.chetanahegde.in with most recent updates. 1 MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING Syllabus: What is Android? Obtaining the required tools, Anatomy

More information

OPTIMIZING ANDROID UI PRO TIPS FOR CREATING SMOOTH AND RESPONSIVE APPS

OPTIMIZING ANDROID UI PRO TIPS FOR CREATING SMOOTH AND RESPONSIVE APPS OPTIMIZING ANDROID UI PRO TIPS FOR CREATING SMOOTH AND RESPONSIVE APPS @CYRILMOTTIER GET TO KNOW JAVA DON T USE BOXED TYPES UNNECESSARILY HashMap hashmap = new HashMap();

More information

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu Android Activity LifeCycle Starting Activities Android applications don't start with a call to main(string[])

More information

Android UI Development

Android UI Development Android UI Development Android UI Studio Widget Layout Android UI 1 Building Applications A typical application will include: Activities - MainActivity as your entry point - Possibly other activities (corresponding

More information

COMP4521 EMBEDDED SYSTEMS SOFTWARE

COMP4521 EMBEDDED SYSTEMS SOFTWARE COMP4521 EMBEDDED SYSTEMS SOFTWARE LAB 1: DEVELOPING SIMPLE APPLICATIONS FOR ANDROID INTRODUCTION Android is a mobile platform/os that uses a modified version of the Linux kernel. It was initially developed

More information

Custom Views in Android Tutorial

Custom Views in Android Tutorial Custom Views in Android Tutorial The Android platform provides an extensive range of user interface items that are sufficient for the needs of most apps. However, there may be occasions on which you feel

More information

Fig. 2.2 New Android Application dialog. 2.3 Creating an App 41

Fig. 2.2 New Android Application dialog. 2.3 Creating an App 41 AndroidHTP_02.fm Page 41 Wednesday, April 30, 2014 3:00 PM 2.3 Creating an App 41 the Welcome app s TextView and the ImageViews accessibility strings, then shows how to test the app on an AVD configured

More information

Graphics Support in Android

Graphics Support in Android Graphics Support in Android Android and Graphics The Android pla4orm supports both 2D and 3D graphics: 2D graphics is powered by a custom library High performance 3D graphics is based on the OpenGL ES

More information

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment FRAGMENTS Fragments An activity is a container for views When you have a larger screen device than a phone like a tablet it can look too simple to use phone interface here. Fragments Mini-activities, each

More information

Google Maps Troubleshooting

Google Maps Troubleshooting Google Maps Troubleshooting Before you go through the troubleshooting guide below, make sure that you ve consulted the class FAQ, Google s Map Activity Tutorial, as well as these helpful resources from

More information

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento Getting started: Installing IDE and SDK Marco Ronchetti Università degli Studi di Trento Alternative: Android Studio http://developer.android.com/develop/index.html 2 Tools behind the scenes dx allows

More information

Android Application Development

Android Application Development Android Application Development Octav Chipara What is Android A free, open source mobile platform A Linux-based, multiprocess, multithreaded OS Android is not a device or a product It s not even limited

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi Introduction An application is composed of at least one Activity GUI It is a software component that stays behind a GUI (screen) Activity It runs inside the

More information

EMBEDDED SYSTEMS PROGRAMMING Android Services

EMBEDDED SYSTEMS PROGRAMMING Android Services EMBEDDED SYSTEMS PROGRAMMING 2016-17 Android Services APP COMPONENTS Activity: a single screen with a user interface Broadcast receiver: responds to system-wide broadcast events. No user interface Service:

More information

TextView. A label is called a TextView. TextViews are typically used to display a caption TextViews are not editable, therefore they take no input

TextView. A label is called a TextView. TextViews are typically used to display a caption TextViews are not editable, therefore they take no input 1 UI Components 2 UI Components 3 A label is called a TextView. TextView TextViews are typically used to display a caption TextViews are not editable, therefore they take no input - - - - - - -

More information

Chapter 2 Welcome App

Chapter 2 Welcome App 2.8 Internationalizing Your App 1 Chapter 2 Welcome App 2.1 Introduction a. Android Studio s layout editor enables you to build GUIs using drag-and-drop techniques. b. You can edit the GUI s XML directly.

More information

Programming with Android: Animations, Menu, Toast and Dialogs. Luca Bedogni. Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna

Programming with Android: Animations, Menu, Toast and Dialogs. Luca Bedogni. Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna Programming with Android: Animations, Menu, Toast and Dialogs Luca Bedogni Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna Animations vmake the components move/shrink/color vmainly

More information

ECOM 5341 Mobile Computing(Android) Eng.Ruba A. Salamah

ECOM 5341 Mobile Computing(Android) Eng.Ruba A. Salamah ECOM 5341 Mobile Computing(Android) 1 Eng.Ruba A. Salamah Lecture # 2 Android Tools Objectives Understand Android Tools Setup Android Development Environment Create HelloWorld Application Understand HelloWorld

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Alberto Monge Roffarello Politecnico di Torino, 2017/2018 Some slides and figures are taken from the Mobile Application Development (MAD) course Disclaimer

More information

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State EMBEDDED SYSTEMS PROGRAMMING 2016-17 Application Tip: Saving State THE PROBLEM How to save the state (of a UI, for instance) so that it survives even when the application is closed/killed The state should

More information

Android Navigation Drawer for Sliding Menu / Sidebar

Android Navigation Drawer for Sliding Menu / Sidebar Android Navigation Drawer for Sliding Menu / Sidebar by Kapil - Tuesday, December 15, 2015 http://www.androidtutorialpoint.com/material-design/android-navigation-drawer-for-sliding-menusidebar/ YouTube

More information

Getting Started With Android Feature Flags

Getting Started With Android Feature Flags Guide Getting Started With Android Feature Flags INTRO When it comes to getting started with feature flags (Android feature flags or just in general), you have to understand that there are degrees of feature

More information

Security model. Marco Ronchetti Università degli Studi di Trento

Security model. Marco Ronchetti Università degli Studi di Trento Security model Marco Ronchetti Università degli Studi di Trento Security model 2 Android OS is a multi-user Linux in which each application is a different user. By default, the system assigns each application

More information

Understanding Application

Understanding Application Introduction to Android Application Development, Android Essentials, Fifth Edition Chapter 4 Understanding Application Components Chapter 4 Overview Master important terminology Learn what the application

More information

Change in Orientation. Marco Ronchetti Università degli Studi di Trento

Change in Orientation. Marco Ronchetti Università degli Studi di Trento 1 Change in Orientation Marco Ronchetti Università degli Studi di Trento Change in orientation Change in orientation For devices that support multiple orientations, Android detects a change in orientation:

More information

Android Workshop: Model View Controller ( MVC):

Android Workshop: Model View Controller ( MVC): Android Workshop: Android Details: Android is framework that provides java programmers the ability to control different aspects of smart devices. This interaction happens through the Android SDK (Software

More information

Action Bar. Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps.

Action Bar. Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps. 1 Action Bar Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps. 1) App Icon 3) Action Buttons 2)View Control 4) Action Overflows

More information

ELET4133: Embedded Systems. Topic 15 Sensors

ELET4133: Embedded Systems. Topic 15 Sensors ELET4133: Embedded Systems Topic 15 Sensors Agenda What is a sensor? Different types of sensors Detecting sensors Example application of the accelerometer 2 What is a sensor? Piece of hardware that collects

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING 1) What is Android? Important Android Questions It is an open-sourced operating system that is used primarily

More information

Android Tutorial: Part 3

Android Tutorial: Part 3 Android Tutorial: Part 3 Adding Client TCP/IP software to the Rapid Prototype GUI Project 5.2 1 Step 1: Copying the TCP/IP Client Source Code Quit Android Studio Copy the entire Android Studio project

More information

CS 234/334 Lab 1: Android Jump Start

CS 234/334 Lab 1: Android Jump Start CS 234/334 Lab 1: Android Jump Start Distributed: January 7, 2014 Due: Friday, January 10 or Monday, January 13 (in-person check off in Mobile Lab, Ry 167). No late assignments. Introduction The goal of

More information

Activities and Fragments

Activities and Fragments Activities and Fragments 21 November 2017 Lecture 5 21 Nov 2017 SE 435: Development in the Android Environment 1 Topics for Today Activities UI Design and handlers Fragments Source: developer.android.com

More information

CE881: Mobile & Social Application Programming

CE881: Mobile & Social Application Programming CE881: Mobile & Social Application Programming, s, s and s Jialin Liu Senior Research Officer Univerisity of Essex 6 Feb 2017 Recall of lecture 3 and lab 3 :) Please download Kahoot or open a bowser and

More information

Stanislav Rost CSAIL, MIT

Stanislav Rost CSAIL, MIT Session 2: Lifecycles, GUI Stanislav Rost CSAIL, MIT The Plan 1 Activity lifecycle Service lifecycle 2 Selected GUI elements UI Layouts 3 Hands on assignment: RoboChat Application GUI Design Birth, death,

More information