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 application Set of permissions app requires All Activities
Activity Activity Class: android.app.activity Usually associated with a screen Must have at least one entry point for application
Activity Lifecycle An Activity can be in one of several states: Created oncreate() Started onstart() Resumed onresume() In foreground Running NOTE: onresume() not called repeatedly while activity is running Paused onpaused() Partially obscured Cannot receive user input Not running Stopped onstop() Completely hidden State information saved Not running Destroyed ondestroy()
Activity Files By default, you will have an Activity called MainActivity When an Activity is created, there are two main files: Java file MainActivity.java Layout file activity_main.xml It is possible to add/change GUI elements in Java code However, usually easier to use XML/Design tool
GUI Basics
Activity Layout When you open activity_main.xml, you can choose two views (tabs at bottom) Text the actual XML file Design drag-and-drop interface for adding GUI elements When you select a GUI element, its properties are listed on the right
Activity Layout
Views and ViewGroups View Base class for all user interface classes ViewGroup Inherits from View Base class for layouts of Views
Example: Adding a Button Let s add a button to start a second Activity from our main Activity Drag a Button onto the layout Change the text on the button with the text property
Example: Changing the ID of the Button The id property allows us to identify the button later in code In this example, we ll change the id to secondactivitybutton
Example: Attaching Code to a Button In our main activity, oncreate() will set up the layout based on the XML file We need to tell the activity to listen for certain events in this case, clicking the button There are two ways to do this: Method 1 Set the onclick property for the button to point to a function in MainActivity Method 2 Attach a new listener directly to the button
Example: Attaching Code to a Button (Method 1) Open activity_main.xml Select our button Write clickme in the onclick property Open MainActivity.java Add a new function clickme : public void clickme(view view) { // Code goes here }
Example: Attaching Code to a Button (Method 2) To create a separate listener, we will do the following in oncreate(): Find our button by ID Attach a OnClickListener to the button
Example: Attaching Code to a Button (Method 2) Find our button by ID (in oncreate()) R contains all our resources To get the ID: R.id.secondActivityButton To get the actual button: Button activitybutton = (Button) findviewbyid(r.id.secondactivitybutton);
Example: Attaching Code to a Button (Method 2) Attach a OnClickListener to the button setonclicklistener() attaches a listener View.OnClickListener interface Specifies one function: onclick(view view) Several ways we could define an OnClickListener: Create a separate class that implements View.OnClickListener Create an anonymous class To create an anonymous class for this: activitybutton.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { // Code for button click here } });
Printing Messages For now, let s have the button print a message to the console Console printouts in Android Log class Different functions, depending on level of message: Log.v() verbose Log.d() debug Log.i() info Log.w() warning Log.e() error Pass in tag and message Good idea to make constant for tag: private static final String TAG = MyActivity ; Example: Log.v(TAG, What happened? );
Example: Consult the Logs Logs will print to logcat Can also search for keywords
Example: Message in a Button When you click the button, the verbose log will print the message activitybutton.setonclicklistener(new View.OnClickListener() { public void onclick(view view) { Log.v( MyActivity, YOU PUSHED THE BUTTON! ); } });
Intents and Activities
Original Intent Ultimately, we wanted this button to launch a new activity To do this, we need to: Create a new Activity Have the button create an Intent when it is clicked
Creating a New Activity To create a new Activity: Right-click on app or the project folder Select New Activity Blank Activity
Creating a New Activity I have named this activity SecondActivity The other names/strings will adjust accordingly
The New Activity There are now two more files: SecondActivity.java activity_second.xml
String Resources Among many other resources, you have res/values/strings.xml This contains the strings for your application In this case, I have added a new string with ID second_message
String IDs Back in activity_second.xml, I have changed the text property of the text onscreen to be: @string/second_message I also changed the ID while I was there:
Intent Intent Class: android.content.intent Used to make a request to the Android OS Explicit start a specific Activity or app Implicit start an Activity or app based on criteria E.g., takes photos presented with list of apps that take photos Can also pass data between activities Use putextra() to include additional data ( extras )
Launching One Activity from Another First, we will create an Intent: Intent startintent = new Intent(getApplicationContext(), SecondActivity.class); Then, we will start an activity using this intent: startactivity(startintent); Now, when we click the button, we will see the second activity
Launching One Activity from Another
What Happened to the First Activity? When you start an Activity, the first activity stops When you go back, it will start up again
Passing Extra Data You can pass data between Activity using extra data In MainActivity.java: public final static String EXTRA_MESSAGE = "com.cs370.reale.message"; Intent startintent = new Intent(getApplicationContext(), SecondActivity.class); String message = "FOR THE EMPEROR!!!"; startintent.putextra(extra_message, message); startactivity(startintent); putextra() takes string tag and data Lots of different options for data can also pass in Object if implement Serializable!
Getting Extra Data In SecondActivity.java, let s override our text field with the string we get from MainActivity: // Get the Intent Intent intent = getintent(); // Get the string String message = intent.getstringextra(mainactivity.extra_message); // Set the text message TextView textmessage = (TextView) findviewbyid(r.id.secondmessage); textmessage.settext(message);
Getting Extra Data
Threads
UI Thread All interactions with the user interface are handled by the UI thread As such, you do NOT want to do any major processing inside this thread! app will be unresponsive To perform long-running processes, you have a few options: Worker threads AsyncTask Service IntentService
Worker Threads Worker thread Extends Java Thread or implements Runnable Problem: how do you update UI elements? Solution: post() All View classes have this Pass in Runnable class executes code on UI thread
Example: Worker Threads Example: create anonymous Thread, sleep 5 seconds, then change text on secondmessage NOTE the call to start()! new Thread(new Runnable() { public void run() { SystemClock.sleep(5000); findviewbyid(r.id.secondmessage).post(new Runnable() { public void run() { ((TextView)findViewById(R.id.secondMessage)).setText("TIME IS UP!"); } }); } }).start(); // <-- NOTE: NEED THIS
Example: Worker Threads 5 seconds later
References Android Application Development in 24 Hours (4 th edition): http://www.amazon.com/gp/product/0672337398/ Android Starting Another Activity Tutorial: http://developer.android.com/training/basics/firstapp/starting-activity.html