developing in android

26
Developing in Android What to do after you have the SDK installed

Upload: christopher-decker

Post on 10-May-2015

1.414 views

Category:

Documents


2 download

DESCRIPTION

IEEE Seminar notes

TRANSCRIPT

Page 1: Developing in android

Developing in Android

What to do after you have the SDK installed

Page 2: Developing in android

Outline

• Creating a new project• XML/pragmatically constructing layouts•  Initializing the UI (listeners, ect)• Permissions• Calling other activities• Overview of other functionality (bluetooth, maps, Camera,

ect, preferances)• Additional Resources (google is your best friend)• Workshop

Page 3: Developing in android

Creating a project

• file->new->project->android project

Page 4: Developing in android

Project Creation Fields

Project NameThis is the Eclipse Project name — the name of the directory that will contain the project files.

Application NameThis is the human-readable title for your application — the name that will appear on the Android device.

Package NameThis is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated.

Create ActivityThis is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.

Min SDK VersionThis value specifies the minimum API Level required by your application. 

Page 5: Developing in android

New Project

Page 6: Developing in android

Activity Lifecycle• onCreate()• onRestart()• onStart()• onResume()• onPause()• onStop()• onDestroy()

More in Depth Explanation:http://developer.android.com/guide/topics/fundamentals.html

Page 7: Developing in android

UI Creation

Page 8: Developing in android

Location of XML

Page 9: Developing in android

XML Layout

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <TextView        android:id="@+id/label"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Type here:"/>    <EditText        android:id="@+id/entry"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:background="@android:drawable/editbox_background"        android:layout_below="@id/label"/>    <Button        android:id="@+id/ok"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/entry"        android:layout_alignParentRight="true"        android:layout_marginLeft="10dip"        android:text="OK" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toLeftOf="@id/ok"        android:layout_alignTop="@id/ok"        android:text="Cancel" /></RelativeLayout>

Page 10: Developing in android

XML vs Programmatically

<Button        android:id="@+id/ok"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/entry"        android:layout_alignParentRight="true"        android:layout_marginLeft="10dip"        android:text="OK" />

//intiate buttonButton ok= new Button(this);//assign ID for later referanceok.setId(R.id.ok);

//sets paramiters, wraps contentLayoutParams params = new LayoutParams (ViewGroup.Layout         Params.WRAP_CONTENT,        ViewGroup.LayoutParams.WRAP_CONTENT);//sets position within the layoutparams.addRule(RelativeLayout.layout_below, R.id.entry );params.addRule(RelativeLayout.layout_alignParentRight);//sets the left marginparams.setMargins(10,0,0,0);

//sets the params to the buttonok.setLayoutParams(params);//sets the textok.setText("OK");//adds the button as a childlayout.addView(ok);

Page 11: Developing in android

Initializing the UI

 public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.view_name);        //add listeners    }

Page 12: Developing in android

Button Listener

Button btnName = (Button) findViewById(R.id.btnId);btnNamet.setOnClickListener(new View.OnClickListener() {    public void onClick(View v) {   //sets what the button dose when clicked           } });

Page 13: Developing in android

onTouchListener

FrameLayout main = (FrameLayout) findViewById(R.id.main_view);      //set touch listenermain.setOnTouchListener(new View.OnTouchListener() {    public boolean onTouch(View v, MotionEvent e) {        //x and y coordinates        float x = e.getX();        float y = e.getY();                    //MotionEvent.ACTION_DOWN=finger presses down        //MotionEvent.ACTION_UP=finger lifts up        //MotionEvent.ACTION_MOVE=change in postion between UP and DOWN         if(e.getAction()==MotionEvent.ACTION_DOWN){             //do something        }    return true;     }});

Page 14: Developing in android

Manifest.XML

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.RIT.exersize2"      android:versionCode="1"      android:versionName="1.0">      <uses-permission android:name="android.permission.CAMERA" />    <application android:icon="@drawable/icon"             android:label="@string/app_name">        <activity android:name=".exersize2"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest> 

Page 15: Developing in android

Some Common PermissionsACCESS_FINE_LOCATION Allows an application to access fine (e.g., GPS) location

ACCESS_NETWORK_STATE Allows applications to access information about networks

BATTERY_STATS Allows an application to collect battery statistics

BLUETOOTH Allows applications to connect to paired bluetooth devices

CALL_PHONE Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.

CAMERA Required to be able to access the camera device.

EXPAND_STATUS_BAR Allows an application to expand or collapse the status bar.

FLASHLIGHT Allows access to the flashlight

INTERNET Allows applications to open network sockets.

MODIFY_AUDIO_SETTINGS Allows an application to modify global audio settings

REBOOT Required to be able to reboot the device.

RECEIVE_SMS Allows an application to monitor incoming SMS messages, to record or perform processing on them.

SEND_SMS Allows an application to send SMS messages.

SET_ALARM Allows an application to broadcast an Intent to set an alarm for the user.

SET_ORIENTATION Allows low-level access to setting the orientation (actually rotation) of the screen.

SET_TIME Allows applications to set the system time

VIBRATE Allows access to the vibrator

WRITE_SMS Allows an application to write SMS messages.

Page 16: Developing in android

Calling Other Apps

Intent intent = new Intent("classpath");startActivity(intent);        or:startActivityForResult(scan, 0);

 public void onActivityResult(int requestCode, int resultCode, Intent intent) {        if (requestCode == 0) {            if (resultCode == RESULT_OK) {                //name value pair retrieval                String contents = intent.getStringExtra("SCAN_RESULT");                            } else if (resultCode == RESULT_CANCELED) {                //fail            }        }    }

Page 17: Developing in android

Bluetooth

1. Ensure that the devise supports Bluetooth2. Turn Bluetooth on if not already3.  Find Device

 Query Pared Devices  Discover Device

4.  Connecting to a device is almost identical to connecting via TCP

5. Communication between devices is almost identical to TCP as well

Bluetooth Tutorial:http://developer.android.com/guide/topics/wireless/bluetooth.html

Page 18: Developing in android

Location// Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager)       this.getSystemService(Context.LOCATION_SERVICE);  // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() {      public void onLocationChanged(Location location) {          // Called when a new location is found by the network location provider.                 makeUseOfNewLocation(location);      }     public void onStatusChanged(String provider, int status, Bundle extras) {}      public void onProviderEnabled(String provider) {}      public void onProviderDisabled(String provider) {}  };

 //Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,             locationListener); //for GPS use LocationManager.GPS_PROVIDER

Tutorial: http://developer.android.com/guide/topics/location/obtaining-user-

location.html

Page 19: Developing in android

Using the Camera: Activitypackage android.cameratest;

import java.io.IOException;import android.app.Activity;import android.graphics.PixelFormat;import android.hardware.Camera;import android.os.Bundle;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.view.View;import android.view.Window;import android.view.WindowManager;

public class CameraTest extends Activity implements SurfaceHolder.Callback, View.OnClickListener{Bundle bundle;SurfaceView mSurfaceView;SurfaceHolder mSurfaceHolder;Camera mCamera;boolean mPreviewRunning;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {     super.onCreate(bundle);     getWindow().setFormat(PixelFormat.TRANSLUCENT);     requestWindowFeature(Window.FEATURE_NO_TITLE);     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,     WindowManager.LayoutParams.FLAG_FULLSCREEN);     setContentView(R.layout.camera_surface);     mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);     mSurfaceView.setOnClickListener((android.view.View.OnClickListener) this);     mSurfaceHolder = mSurfaceView.getHolder();     mSurfaceHolder.addCallback(this);     mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);    }

Page 20: Developing in android

Using The Camera: Activity/*** When the surface is first created.* Open the camera harware.*/public void surfaceCreated(SurfaceHolder holder) {mCamera = Camera.open();}/**     * Called when the surface/format of the surface changes. Can be change in orientation or screen off.     * Called after surfaceCreated. Set up camera settings.     */public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {if (mPreviewRunning) {mCamera.stopPreview();}Camera.Parameters p = mCamera.getParameters();p.setPreviewSize(width, height);mCamera.setParameters(p);

try {mCamera.setPreviewDisplay(holder);} catch (IOException e) {e.printStackTrace();}mCamera.startPreview();mPreviewRunning = true;}/*** Called when surface is destroyed.  When screen is black.*/public void surfaceDestroyed(SurfaceHolder holder) {mCamera.stopPreview();mPreviewRunning = false;                mCamera.release(); }

Page 21: Developing in android

Using The Camera: Activity

/*** The camera callback. Put code that deals with the image returned in byte form.* */Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

public void onPictureTaken(byte[] imageData, Camera c) {}/** What is done with the data (imageData) byte stream. * Can save it to files or edit it. */};/*** Takes the picture when the screen is touched.* @param v*/public void onClick(View v) {//Call on the camera  hardware to take a picture.mCamera.takePicture(null, mPictureCallback, mPictureCallback);mCamera.startPreview();mPreviewRunning = true;}    }

Page 22: Developing in android

    Flow of Taking a Picture

Page 23: Developing in android

Additional Resources 

API: http://developer.android.com/reference/packages.html

Developers guide: http://developer.android.com/guide/index.html

http://stackoverflow.com is a great place to ask questions

When in doubt, Google knows all

Page 24: Developing in android

Workshop

Implement an application which reads a URL from a QR code and then opens the page in a browser.

Page 25: Developing in android

API: http://developer.android.com/reference/packages.html

Barcode Reader:http://code.google.com/p/zxing/

Normal Project:http://people.rit.edu/cld8812/Exersize2.zip

Easy Project:http://people.rit.edu/cld8812/Exersize2Easy.zip

Page 26: Developing in android

Thanks for Coming!

The completed workshop can be found at:

http://people.rit.edu/cld8812/ExersizeFinal.zip