Androidppt 1
Upcoming SlideShare
Loading in...5
×
 

Androidppt 1

on

  • 940 views

 

Statistics

Views

Total Views
940
Views on SlideShare
940
Embed Views
0

Actions

Likes
3
Downloads
79
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Androidppt 1 Androidppt 1 Presentation Transcript

    • Android DevelopmentOverview
    • Android architecture
    • Android Application Lifecycle
    • On createimport android.app.Activity;public class MainActivity extends Activity{TextView mTextView; // Member variable for text view in the layout@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// Set the user interface layout for this Activity// The layout file is defined in the project res/layout/main_activity.xml filesetContentView(R.layout.main_activity);mTextView = (TextView) findViewById(R.id.text_message);mTextView.setText(“Hello World”);}}
    • AndroidManifest.xml<activity android:name=".MainActivity" android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    • Fundamental Android UI Design
    • Frame Layout<?xml version="1.0" encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"><ImageViewandroid:id="@+id/ImageView01"android:layout_height="fill_parent"android:layout_width="fill_parent"android:src="@drawable/lake"android:scaleType="matrix"></ImageView><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:textColor="#000"android:textSize="40dp"android:text="@string/top_text" /><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/bottom_text"android:layout_gravity="bottom"android:gravity="right"android:textColor="#fff"android:textSize="50dp" /></FrameLayout>
    • Liner Layout 1<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:background="@drawable/blue"android:layout_width="fill_parent"android:layout_height="wrap_content"><TextViewandroid:background="@drawable/box"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/linear_layout_1_top"/><TextViewandroid:background="@drawable/box"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/linear_layout_1_middle"/><TextViewandroid:background="@drawable/box"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/linear_layout_1_bottom"/></LinearLayout>
    • Liner layout 2<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid:background="@drawable/red"android:layout_width="0dip"android:layout_height="fill_parent"android:layout_weight="1"/><TextViewandroid:background="@drawable/green"android:layout_width="0dip"android:layout_height="fill_parent"android:layout_weight="1"/><TextViewandroid:background="@drawable/blue"android:layout_width="0dip"android:layout_height="fill_parent"android:layout_weight="1"/><TextViewandroid:background="@drawable/yellow"android:layout_width="0dip"android:layout_height="fill_parent"android:layout_weight="1"/></LinearLayout>
    • Liner Layout 3<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="vertical"><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center_vertical"android:paddingRight="0dip"android:background="@android:drawable/edit_text"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/linear_layout_10_from"android:textColor="?android:attr/textColorSecondary"/><EditTextandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:singleLine="true"android:background="@null"/><ImageButtonandroid:src="@android:drawable/star_big_on"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout></LinearLayout>
    • Relativity Layout<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:background="@drawable/blue"android:padding="10dip"><TextViewandroid:id="@+id/label"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/relative_layout_2_instructions"/><EditTextandroid:id="@+id/entry"android:layout_width="fill_parent"android:layout_height="wrap_content"android:background="@android:drawable/editbox_background"android:layout_below="@id/label"/><Buttonandroid: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="@string/relative_layout_2_ok" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_toLeftOf="@id/ok"android:layout_alignTop="@id/ok"android:text="@string/relative_layout_2_cancel" /></RelativeLayout>
    • ListViewmain.xml<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="#FFFFFF"><ListViewandroid:id="@+id/listView1"android:layout_width="fill_parent"android:layout_height="fill_parent" /></LinearLayout>
    • ListViewlistview_header_row.xml<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:id="@+id/txtHeader"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center_vertical"android:layout_alignParentTop="true"android:layout_alignParentBottom="true"android:textStyle="bold"android:textSize="22dp"android:textColor="#FFFFFF"android:padding="10dp"android:text="Weather Photos"android:background="#336699" /></LinearLayout>
    • ListViewlistview_item_row.xml<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="10dp"><ImageView android:id="@+id/imgIcon"android:layout_width="wrap_content"android:layout_height="fill_parent"android:gravity="center_vertical"android:layout_alignParentTop="true"android:layout_alignParentBottom="true"android:layout_marginRight="15dp"android:layout_marginTop="5dp"android:layout_marginBottom="5dp" /><TextView android:id="@+id/txtTitle"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center_vertical"android:layout_alignParentTop="true"android:layout_alignParentBottom="true"android:textStyle="bold"android:textSize="22dp"android:textColor="#000000"android:layout_marginTop="5dp"android:layout_marginBottom="5dp" /></LinearLayout>
    • ListView (ArrayAdapter)public class WeatherAdapter extends ArrayAdapter<Weather>{Context context;int layoutResourceId;Weather data[] = null;public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {super(context, layoutResourceId, data);this.layoutResourceId = layoutResourceId;this.context = context;this.data = data;}public View getView(int position, View convertView, ViewGroup parent) {View row = convertView;WeatherHolder holder = null;if(row == null){LayoutInflater inflater = ((Activity)context).getLayoutInflater();row = inflater.inflate(layoutResourceId, parent, false);holder = new WeatherHolder();holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);row.setTag(holder);}else{holder = (WeatherHolder)row.getTag();}Weather weather = data[position];holder.txtTitle.setText(weather.title);holder.imgIcon.setImageResource(weather.icon);return row;}static class WeatherHolder{ImageView imgIcon;TextView txtTitle;}}public class MainActivity extends Activity {private ListView listView1;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Weather weather_data[] = new Weather[]{new Weather(R.drawable.weather_cloudy, "Cloudy"),new Weather(R.drawable.weather_showers, "Showers"),new Weather(R.drawable.weather_snow, "Snow"),new Weather(R.drawable.weather_storm, "Storm"),new Weather(R.drawable.weather_sunny, "Sunny")};WeatherAdapter adapter = new WeatherAdapter(this,R.layout.listview_item_row, weather_data);listView1 = (ListView)findViewById(R.id.listView1);View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row,null);listView1.addHeaderView(header);listView1.setAdapter(adapter);}}public class Weather {public int icon;public String title;public Weather(){super();}public Weather(int icon, String title) {super();this.icon = icon;this.title = title;}}
    • IntentIntents are used as a message-passing mechanismthat works both within your application andbetween applications. You can use Intents to dothe following:• Explicitly start a particular Service or Activityusing its class name• Start an Activity or Service to perform an actionwith (or on) a particular piece of data• Broadcast that an event has occurred
    • Intent ExamplesExplicitly Starting New ActivitiesIntent intent = new Intent(MyActivity.this, MyOtherActivity.class);startActivity(intent);Passing Parameter from one activity to anotherIntent intent = new Intent(MyActivity.this, MyOtherActivity.class);data.putExtra("data", "test data");startActivity(intent);Retrieving data from previous activityBundle b = intent.getExtras();String data = b.getString("data");Selecting a Contact Examplepublic class ContactPickerTester extends Activity {public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.contactpickertester);Button button = (Button)findViewById(R.id.pick_contact_button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View _view) {Intent intent = new Intent(Intent.ACTION_PICK,Uri.parse("content://contacts/"));startActivityForResult(intent, PICK_CONTACT);}});}}public void onActivityResult(int reqCode, int resCode, Intent data) {super.onActivityResult(reqCode, resCode, data);switch(reqCode) {case (PICK_CONTACT) : {if (resCode == Activity.RESULT_OK) {Uri contactData = data.getData();Cursor c = getContentResolver().query(contactData, null, null, null,null);c.moveToFirst();String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));c.close();TextView tv =(TextView)findViewById(R.id.selected_contact_textview);tv.setText(name);}break;}default: break;}}
    • FragmentA Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity tobuild a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, whichhas its own lifecycle, receives its own input events, and which you can add or remove while the activity is running.<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="match_parent"><fragment android:name="com.example.news. ArticleListFragment"android:id="@+id/list"android:layout_weight="1"android:layout_width="0dp"android:layout_height="match_parent" /><fragment android:name="com.example.news. ArticleReaderFragment"android:id="@+id/viewer"android:layout_weight="2"android:layout_width="0dp"android:layout_height="match_parent" /></LinearLayout>
    • Fragmentimport android.support.v4.app.ListFragment; android.app.Fragment (for version 3.0+)import android.support.v4.app.Fragment; android.app.ListFragment (for version 3.0)public class ArticleListFragment extends ListFragment {public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);int layout = android.R.layout.simple_list_item_1;setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.ArticleList));}}public class ArticleFragment extends Fragment {public View onCreateView(LayoutInflater inflater, ViewGroup container,return inflater.inflate(R.layout.article_view, container, false);}}
    • Action Bar (android 3.0+)• Provide a dedicated space for identifying the application brand and user location.• This is accomplished with the app icon or logo on the left side and the activity title. You might chooseto remove the activity title, however, if the current view is identified by a navigation label, such as thecurrently selected tab.• The action bar provides built-in tab navigation for switching between fragments. It also offers a drop-down list you can use as an alternative navigation mode or to refine the current view (such as to sort alist by different criteria).• Make key actions for the activity (such as "search", "create", "share", etc.) prominent and accessible tothe user in a predictable way.<manifest ... ><uses-sdk android:minSdkVersion="4"android:targetSdkVersion="11" /> ActionBar actionBar = getActionBar();actionBar.hide();...</manifest>
    • Action Bar and FragmentsgetActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);getActionBar().setDisplayOptions((int) Window.FEATURE_NO_TITLE);Tab tab = getActionBar().newTab().setText("Category").setTabListener(new SurveyTabListener<CategoryFragment>(this, "", CategoryFragment.class));Tab tab1 = getActionBar().newTab().setText("Create").setTabListener(new SurveyTabListener<CreatePollFragement>(this, "", CreatePollFragement.class));Tab tab2 = getActionBar().newTab().setText("Results").setTabListener(new SurveyTabListener<MyPollFragement>(this, "", MyPollFragement.class));public class SurveyTabListener<T extends Fragment> implements TabListener{private Fragment mFragment;private final FragmentActivity mActivity;private final String mTag;private final Class<T> mClass;public SurveyTabListener(FragmentActivity activity, String tag, Class<T> clz) {mActivity = activity;mTag = tag;mClass = clz;}public void onTabSelected(Tab tab, FragmentTransaction ignoreft) {FragmentManager fragMgr ((FragmentActivity)mActivity).getSupportFragmentManager();FragmentTransaction ft = fragMgr.beginTransaction();if (mFragment == null) {// If not, instantiate and add it to the activitymFragment = Fragment.instantiate(mActivity, mClass.getName());ft.add(android.R.id.content, mFragment, mTag);} else {ft.attach(mFragment);}ft.commit();}public void onTabReselected(Tab tab, FragmentTransaction ignoreft) {}public void onTabUnselected(Tab tab, FragmentTransaction ft) {}}
    • ServiceServices are started, stopped, and controlled from otherapplication components, including Activitiespublic class MyService extends Service {public void onCreate() {super.onCreate();}public IBinder onBind(Intent intent) {}<service android:enabled="true" android:name=".MyService"/>private void startService() {Intent intent = new Intent(this, MyService.classstartService(intent);}
    • AsyncTask• The AsyncTask class implements a best practice pattern for moving your time-consuming operations ontoa background Thread and synchronizing with the UI Thread for updates and when the processing iscomplete. It offers the convenience of event handlers synchronized with the GUI Thread to let you updateViews and other UI elements to report progress or publish results when your task is complete.• AsyncTask handles all the Thread creation, management, and synchronization, enabling you to create anasynchronous task consisting of processing to be done in the background and UI updates to be performedboth during the processing, and once its complete.private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {protected Long doInBackground(URL... urls) {int count = urls.length;long totalSize = 0;for (int i = 0; i < count; i++) {totalSize += Downloader.downloadFile(urls[i]);publishProgress((int) ((i / (float) count) * 100));// Escape early if cancel() is calledif (isCancelled()) break;}return totalSize;}protected void onProgressUpdate(Integer... progress) {setProgressPercent(progress[0]);}protected void onPostExecute(Long result) {showDialog("Downloaded " + result + " bytes");}}
    • Android DBpublic class DBTest {private DatabaseHelper helper;private SQLiteStatement insertStmt;private static final String INSERT = "insert into insertTest (text) values (?)";public DBTest(Context context){helper = new DatabaseHelper(context);db = helper.getWritableDatabase();insertStmt = db.compileStatement(INSERT);}public void close(){ helper.close();}public void insert(String test){insertStmt.bindString(1, test);insertStmt.executeInsert();}public Set<String> getText(){Cursor cursor = db.query("upload", new String[] {“text"}, null, null, null, null, "path desc");Set<String> texts = new HashSet<String>();if (cursor != null && cursor.moveToFirst()){do{texts.add(cursor.getString(0));}while(cursor.moveToNext());}return texts;}private static class DatabaseHelper extends SQLiteOpenHelper {DatabaseHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}public void onCreate(SQLiteDatabase db) {db.execSQL("CREATE TABLE insertTest (test TEXT)");}public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){db.execSQL("DROP TABLE IF EXISTS insertTest");onCreate(db);}}
    • SAVING SIMPLE APPLICATION DATAThe data-persistence techniques in Android provide options for balancing speed, efficiency, androbustness. Shared Preferences — When storing UI state, user preferences, or application settings, youwant a lightweight mechanism to store a known set of values. Shared Preferences let yousave groups of name/value pairs of primitive data as named preferences. Saved application UI state — Activities and Fragments include specialized event handlers torecord the current UI state when your application is moved to the background. Files — Its not pretty, but sometimes writing to and reading from files is the only way to go.Android lets you create and load files on the devices internal or external media, providingsupport for temporary caches and storing files in publicly accessible folders.
    • CREATING AND SAVING SHARED PREFERENCESSharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS,Activity.MODE_PRIVATE);SharedPreferences.Editor editor = mySharedPreferences.edit();editor.putBoolean("isTrue", true);editor.putFloat("lastFloat", 1f);editor.putInt("wholeNumber", 2);editor.putLong("aNumber", 3l);editor.putString("textEntryValue", "Not Empty");editor.apply();boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);long aNumber = mySharedPreferences.getLong("aNumber", 0);String stringPreference = mySharedPreferences.getString("textEntryValue", "");
    • Saving and Restoring Activity Instance State Using the Lifecycle Handlersprivate static final String TEXTVIEW_STATE_KEY = "TEXTVIEW_STATE_KEY";public void onSaveInstanceState(Bundle saveInstanceState) {TextView myTextView = (TextView)findViewById(R.id.myTextView);saveInstanceState.putString(TEXTVIEW_STATE_KEY, myTextView.getText().toString());super.onSaveInstanceState(saveInstanceState);}public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);TextView myTextView = (TextView)findViewById(R.id.myTextView);String text = "";if (savedInstanceState != null && savedInstanceState.containsKey(TEXTVIEW_STATE_KEY))text = savedInstanceState.getString(TEXTVIEW_STATE_KEY);myTextView.setText(text);}
    • WORKING WITH THE FILE SYSTEMAndroid offers the openFileInput and openFileOutput methods to simplify reading and writing streams fromand to files stored in the applications sandbox.String FILE_NAME = "tempfile.tmp";Create a new output file stream thats private to this application.FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);FileInputStream fis = openFileInput(FILE_NAME);Using the Application File CacheShould your application need to cache temporary files, Android offers both a managed internal cache, and (since Android API level8) an unmanaged external cache. You can access them by calling the getCacheDir and getExternalCacheDir methods,respectively, from the current Context.Storing Publicly Readable Files• DIRECTORY_ALARMS — Audio files that should be available as user-selectable alarm sounds• DIRECTORY_DCIM — Pictures and videos taken by the device• DIRECTORY_DOWNLOADS — Files downloaded by the user• DIRECTORY_MOVIES — Movies• DIRECTORY_MUSIC — Audio files that represent music• DIRECTORY_NOTIFICATIONS — Audio files that should be available as user-selectable notification sounds• DIRECTORY_PICTURES — Pictures• DIRECTORY_PODCASTS — Audio files that represent podcasts• DIRECTORY_RINGTONES — Audio files that should be available as user-selectable ringtones
    • Android Networking and Mobile Cloud Service ProviderStackMobhttps://www.stackmob.com/kinveyhttp://www.kinvey.com/Appceleratorhttp://www.appcelerator.com/Kiihttp://www.kii.com/en/technologyStream SDKhttp://streamsdk.com