android app development notes

6
 Android App Development Notes Android Studio Tips Go to Help  Default Keymap Reference, and use the keyboard shortcuts. Basic Overview of an App Each activity is like one screen in the app. Each activity has a ava !le for the back" end and an #$% !le for the front"end. Activity States &se %o' for debu''in'. Designing the UI  ( o manually add an act ivity, ri'ht click the p acka'e fol der in the )ava folder, 'o to Ne*+, and click Activity . (his 'enerates an #$% !le, ava !le, and updates the manifest !le for you. Create an Interface with Java  ( o create a dy namic interface, create it *ith )ava rather than #$%. n the )ava !le, you must import the typical #$% elements you *ould need such as the layout, buttons, and !elds. Adding properties to widgets  ( o position elements, c reate a ne* ob ect of type R elative%ayout.%ayout- arams. n its constructor, pass in the hei'ht and *idth &se Relative%a yout.%ayout-arams. /RA-012N(EN (3. (hen use the addRule method to add positionin' rules, such as Relative%ayout.1EN(ER04ER (1A%3. (hen, *hen

Upload: tony-jiang

Post on 01-Nov-2015

212 views

Category:

Documents


0 download

TRANSCRIPT

Android App Development NotesAndroid Studio TipsGo to Help Default Keymap Reference, and use the keyboard shortcuts.Basic Overview of an AppEach activity is like one screen in the app. Each activity has a java file for the back-end and an XML file for the front-end.Activity StatesUse Log for debugging.

Designing the UITo manually add an activity, right click the package folder in the Java folder, go to New, and click Activity. This generates an XML file, java file, and updates the manifest file for you.Create an Interface with JavaTo create a dynamic interface, create it with Java rather than XML.In the Java file, you must import the typical XML elements you would need such as the layout, buttons, and fields.Adding properties to widgetsTo position elements, create a new object of type RelativeLayout.LayoutParams. In its constructor, pass in the height and width (Use RelativeLayout.LayoutParams.WRAP_CONTENT). Then use the addRule method to add positioning rules, such as (RelativeLayout.CENTER_VERTICAL). Then, when adding the element to the layout using addView, pass the LayoutParams object as the second parameter.Adding more widgetsAdding more rules, where the first parameter is the positioning, and the second parameter is the element being positioned relative to.Converting DIP to pixelsResources r = getResources(); int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());GridViewEvent HandlingSet an ID for each element.In java file, import views that youre using.Get a reference to the button.Setup event listeners in onCreate. Button buckysButton = (Button) findViewById(R.id.buckysButton);

buckysButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { TextView buckysText = (TextView) findViewById(R.id.buckysText); buckysText.setText("LOL"); } } );Multiple Event Listeners

Returning true in the callback method prevents the event from being handled by another listener.

Gesturesimport android.view.MotionEvent;import android.view.GestureDetector;import android.support.v4.view.GestureDetectorCompat;

Have the activity implement two interfaces:public class MainActivity extends ActionBarActivity implements GestureDetector.OnGestureListener,GestureDetector.OnDoubleTapListener

Implement the interfaces. Ovveride onTouchEvent to check if the event was a gesture.

@Override public boolean onTouchEvent(MotionEvent event) { this.gestureDetector.onTouchEvent(event); return super.onTouchEvent(event);}

FragmentsTo add a fragment, right click on layout and add a new layout resource file.

To create the Java class for your fragment, right click on the package for your project under the java folder, and add a new Java class. Extend the Fragment class. Then, override onCreateView.

@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.top_section_fragment, container, false); return view;}

To add a fragment to the main activity, select at the very bottom of Palette.

Fragments do no interact directly. They use the MainActivity as a medium. In the fragment, import all the widgets and android.app.Activity.

Master Detail FlowTo create a master detail flow, choose master detail flow when creating a new project. Edit the Dummy Content inner class object, edit the detail_webpage_frament.xml, and edit the onCreateView method in WebPageDetailFragment.java

Overflow MenuIn menu there is a file called menu_main.xml. That is for the overflow menu. There is a default item in it for settings.

Put all items in a single group with android:checkableBehavior="single" so that only one can be selected.

Add an item in the group:

OnOptionsItemsSelected in MainActivity is called whenever an item in the menu is clicked. Check for which button was selected here, and carry out callback.

Animations and Transitions

To move an element, must set LayoutParams. Set LayoutParams with RelativeLayout.LayoutParams to set position and ViewGroup.LayoutParams to set size. Use TransitionManager.beginDelayedTransition(layout) to have smooth transition.

Intents

Intents take you from one activity to another.

In the button that leads to a new screen add

android:onClick="onClick"

to the XML. Then just make an onClick method in the java file.

Create a new activity by right clicking the java package and selecting blank activity (or something).

To pass information to an intent use Intent.putExtra(key, value).

To retrieve information in the receiving class: Bundle applesData = this.getIntent().getExtras().toString(key);

Broadcast Intents

Sending a broadcast intent:

Intent i = new Intent(); i.setAction("com.example.android.sendbroadcast"); i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); this.sendBroadcast(i);

Receiving broadcast:

public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Broadcast received!", Toast.LENGTH_LONG);}

Must specify filter in manifest file with and

Threads

Use Runnable, which implements the run() method. Analogous to JavaFX Task.

Rule: Never change any user interface elements inside a runnable. Change the UI in a handler.

Handler handler = new Handler() { @Override public void handleMessage(Message msg) { TextView buckysText = (TextView) findViewById(R.id.buckysText); buckysText.setText("Nice job"); }};

public void clickBuckysButton(View view) { Runnable r = new Runnable () { @Override public void run() { long futureTime = System.currentTimeMillis() + 10000; while (System.currentTimeMillis() < futureTime) { synchronized (this) { try { wait(futureTime - System.currentTimeMillis()); } catch (Exception e) {

} } } handler.sendEmptyMessage(0); } }; Thread buckysThread = new Thread(r); buckysThread.start(); }

Intent Service

Services: Code that runs in the backend.

2 rules for intent services:Need constructor: pass in the name of the class to super.Need to implement onHandleIntent

Register the service in XML manifest with

Start the service like a regular intent. Intent intent = new Intent(this, BuckysIntentService.class); startService(intent);Services

Create a new class using the Service template.

Override onStartCommand, called whenever service started.Override onDestroy.

Does not create a new thread automatically like IntentService, we must make our own.Return Service.START_STICKY so that service will restart if it is ever cancelled.

Start the service like a normal intent.

Bound Services

Must make a new class inside Service class to connect client to service.

Then in client create a reference to MyService and create a ServiceConnection, overriding the methods.

List View

Need something called an adapter to convert objects to list items.

To add event listeners on each item:

Custom ListView Row

Create the design for each fragment in a new XML document.

Create a custom adapter class that extends ArrayAdapter.

Saving Data with SQLite

Create an object to represent each row or entry in the table. Make sure there is an underscore in front of each instance variable name.

Create a class MyDBHandler that handles everything going on with your database. This extends SQLiteOpenHelper. Create constants for your database version, database name, table name, and columns. Create the constructor, override onCreate and onUpgrade. onCreate creates the table with a SQL query.

Notifications

Create a NotificanCompat.Builder object.

To customize the notification: