Top Banner
Tech Talk App Functionality Grooming session of EATL-Prothom Alo Apps Contest 2015
41

Tech Talk: App Functionality (Android)

Jul 28, 2015

Download

Mobile

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Tech Talk: App Functionality (Android)

Tech TalkApp Functionality

Grooming session of EATL-Prothom Alo Apps Contest 2015

Page 3: Tech Talk: App Functionality (Android)

Hello!I am S MAHBUB UZ ZAMANYou can me at mahbub.ninja

Page 4: Tech Talk: App Functionality (Android)

Application Fundamentals

Android apps are written in the Java programming language

Page 5: Tech Talk: App Functionality (Android)

ActivityAn activity represents a single screen with a user interface.

ServiceA service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface.

Content providerEnable applications to share data

Broadcast receiverA Broadcast receiver is a component that responds to system-wide Broadcast announcements.

◦ play music◦ fetch data over network

Database CP

APP 1

APP 2

APP 3

◦ screen has turned off◦ the battery is low◦ a picture was captured◦ Apps can also initiate broadcasts

Page 6: Tech Talk: App Functionality (Android)

Activity

Page 7: Tech Talk: App Functionality (Android)

Activity Life Cycle

◦ sleep◦ home button◦ back button◦ multitask button

◦ onResume()◦ onPause()

Page 8: Tech Talk: App Functionality (Android)

@Override

public void onBackPressed() { … }

@Override

public void onSaveInstanceState(Bundle savedInstanceState) { … }

@Override

public void onRestoreInstanceState(Bundle savedInstanceState) { … }

savedInstanceState.putString("NAME_KEY", "Name");

savedInstanceState.getString("NAME_KEY")

Other Important Methods

Page 9: Tech Talk: App Functionality (Android)
Page 10: Tech Talk: App Functionality (Android)

Service

Page 11: Tech Talk: App Functionality (Android)

Started or Unbounded Service

This service is called by an app component and run in the background even if the caller component is destroyed.

Bounded Service

This service is called by an app component, runs in the background and it offers communication or interaction between the service and the component that launched it. But this type of service is destroyed when all the components that are bound to it are closed

Types Of Service

Page 12: Tech Talk: App Functionality (Android)

Broadcast Receiver Broadcast Intents are used to notify applications of system or application events,

Page 13: Tech Talk: App Functionality (Android)

public class SMSReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent)

{ Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); str += " :"; str += msgs[i].getMessageBody().toString(); str += "\n"; } Toast.makeText(context, str, Toast.LENGTH_SHORT).show();

Intent mainActivityIntent = new Intent(context, MainActivity.class); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(mainActivityIntent); Intent broadcastIntent = new Intent(); broadcastIntent.setAction("SMS_RECEIVED_ACTION"); broadcastIntent.putExtra("sms", str); context.sendBroadcast(broadcastIntent); } }}

Page 14: Tech Talk: App Functionality (Android)

<receiver android:name=".SMSReceiver">

<intent-filter>

<action android:name="android.provider.Telephony.SMS_RECEIVED" />

</intent-filter>

</receiver>

IntentFilter intentFilter;

private BroadcastReceiver intentReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

TextView SMSes = (TextView) findViewById(R.id.tv);

SMSes.setText(intent.getExtras().getString("sms"));

}

};

intentFilter = new IntentFilter();

intentFilter.addAction("SMS_RECEIVED_ACTION");

registerReceiver(intentReceiver, intentFilter);

Page 15: Tech Talk: App Functionality (Android)

Async Task

Page 16: Tech Talk: App Functionality (Android)

.

Async Task

◦ AsyncTask enables proper and easy use of the UI thread. This class allows

to perform background operations and publish results on the UI thread

◦ An asynchronous task is defined by 3 generic types, called Params,

Progress and Result

◦ and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and

onPostExecute.

new DownloadFilesTask().execute(url1, url2, url3);

Page 17: Tech Talk: App Functionality (Android)

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 called

if (isCancelled()) break;

}

return totalSize;

}

protected void onProgressUpdate(Integer... progress) {

setProgressPercent(progress[0]);

}

protected void onPostExecute(Long result) {

showDialog("Downloaded " + result + " bytes");

}

}

Sample Code

Page 18: Tech Talk: App Functionality (Android)

The three types used by an asynchronous task are the following:

1. Params, the type of the parameters sent to the task upon execution.

2. Progress, the type of the progress units published during the background computation.

3. Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

AsyncTask's generic types

private class MyTask extends AsyncTask<Void, Void, Void> {}

Page 19: Tech Talk: App Functionality (Android)

When an asynchronous task is executed, the task goes through 4 steps:

1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

The 4 steps

Page 20: Tech Talk: App Functionality (Android)

service or a thread?

Page 21: Tech Talk: App Functionality (Android)

Service

A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need

Thread

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service

Page 22: Tech Talk: App Functionality (Android)

SQLite Database

Page 23: Tech Talk: App Functionality (Android)

static String DATABSE_NAME = "AVASDB";String TABLE_NAME = "AVAS_BRAIN";static int DATABASE_VERSION_NO = 1;public static SQLiteDatabase db;

public MyAI(Context context) { super(context, DATABSE_NAME, null, DATABASE_VERSION_NO);

}

@Overridepublic void onCreate(SQLiteDatabase db) { String q = "CREATE TABLE " + TABLE_NAME

+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(255));";

db.execSQL(q);}

@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db);

}

SQLiteOpenHelper

Page 24: Tech Talk: App Functionality (Android)

public void addRecord(String name) { db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("Name", name); db.insert(TABLE_NAME, null, values); db.close();

}

public List<String> getRecord() { List<String> recordList = new ArrayList<String>(); try { String selectRecord = "SELECT * from " + TABLE_NAME;

SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectRecord, null);

if (cursor.moveToFirst()) { do { recordList.add(cursor.getString(1)); } while (cursor.moveToNext()); } cursor.close(); db.close(); } catch (Exception e) { e.printStackTrace(); } return recordList;

}

Page 25: Tech Talk: App Functionality (Android)

MyAI db = new MyAI(getApplicationContext());

db.addRecord("A");db.addRecord("B");db.addRecord("C");

Log.v("TAG", db.getRecord().toString());

Activity

Page 26: Tech Talk: App Functionality (Android)

http://sqlitebrowser.org

Page 27: Tech Talk: App Functionality (Android)

Google Map

◦ Add Marker◦ Mark Path◦ Shortest Path

Page 28: Tech Talk: App Functionality (Android)

Better User Experience

Page 29: Tech Talk: App Functionality (Android)

https://code.google.com/apis/console

Steps

Page 30: Tech Talk: App Functionality (Android)
Page 31: Tech Talk: App Functionality (Android)

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!-- Required to show current location -->

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Required OpenGL ES 2.0. for Maps V2 -->

<uses-feature

android:glEsVersion="0x00020000"

android:required="true" />

<meta-data

android:name="com.google.android.maps.v2.API_KEY"

android:value="******************" />

Manifest FIle

Page 32: Tech Talk: App Functionality (Android)

layout file

<?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" >

<fragment

android:id="@+id/map"

android:name="com.google.android.gms.maps.MapFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

</RelativeLayout>

Page 33: Tech Talk: App Functionality (Android)

public class MainActivity extends Activity { private GoogleMap googleMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { initilizeMap(); } catch (Exception e) { e.printStackTrace(); } } private void initilizeMap() { if (googleMap == null) { googleMap = ((MapFragment) getFragmentManager().findFragmentById( R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } } } @Override protected void onResume() { super.onResume(); initilizeMap(); }}

Page 34: Tech Talk: App Functionality (Android)

// latitude and longitude

double latitude = 23.7000;

double longitude = 90.3667;

// create marker

MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Dhaka");

// adding marker

googleMap.addMarker(marker);

Add Marker

Page 35: Tech Talk: App Functionality (Android)

Recycler View

Page 36: Tech Talk: App Functionality (Android)
Page 37: Tech Talk: App Functionality (Android)

LinearLayoutManager llm = new LinearLayoutManager(this);rv.setLayoutManager(llm);rv.setHasFixedSize(true);

GridLayoutManager gridLayoutManager = new GridLayoutManager( this,2);rv.setLayoutManager(gridLayoutManager);rv.setHasFixedSize( true);

android.support.v7.widget.RecyclerView

android.support.v7.widget.CardView

Recylcer View Features

Page 39: Tech Talk: App Functionality (Android)

ANDROID M Developer Preview

1. Permissions

2. Power Improvements (two times longer in standby)

3. USB Type-C will also be supported on Android

Page 40: Tech Talk: App Functionality (Android)

Thanks!

ANY QUESTIONS?