KEMBAR78
Tech Talk: App Functionality (Android) | PDF
Tech Talk
App Functionality
Grooming session of EATL-Prothom Alo Apps Contest 2015
This work is licensed under a Creative
Commons Attribution-NonCommercial 4.0
International License.
“ First, solve the problem. Then, write the code. ” -
John Johnson
Hello!
I am S MAHBUB UZ ZAMAN
You can me at mahbub.ninja
Application Fundamentals
Android apps are written in the Java programming language
“
Activity
An activity represents a single screen with a user interface.
Service
A 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 provider
Enable applications to share data
Broadcast receiver
A 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
Activity
Activity Life Cycle
◦ sleep
◦ home button
◦ back button
◦ multitask button
◦ onResume()
◦ onPause()
@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
Service
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
Broadcast Receiver
Broadcast Intents are used to notify applications of system or application events,
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);
}
}
}
<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);
Async Task
.
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);
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
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> {}
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
service or a thread
?
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
SQLite Database
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);
}
@Override
public void onCreate(SQLiteDatabase db) {
String q = "CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR
(255));";
db.execSQL(q);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
SQLiteOpenHelper
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;
}
MyAI db = new MyAI(getApplicationContext());
db.addRecord("A");
db.addRecord("B");
db.addRecord("C");
Log.v("TAG", db.getRecord().toString());
Activity
http://sqlitebrowser.org
Google Map
◦ Add Marker
◦ Mark Path
◦ Shortest Path
Better User Experience
https://code.google.com/apis/console
Steps
<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
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>
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();
}
}
// 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
Recycler View
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
Android and Arduino
http://developer.android.com/tools/adk/adk.html
https://play.google.com/store/apps/details?id=com.google.android.apps.adk2
ANDROID M Developer Preview
1. Permissions
2. Power Improvements
(two times longer in
standby)
3. USB Type-C will also be
supported on Android
Thanks!
ANY QUESTIONS?
◦ http://developer.android.com/guide/components/fundamentals.html
◦ http://developer.android.com/reference/android/os/AsyncTask.html
◦ http://developer.android.com/guide/components/services.html
◦ https://events.google.com/io2015/
◦ http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/
◦ http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-
cardview-on-android--cms-23465
Resources

Tech Talk: App Functionality (Android)

  • 1.
    Tech Talk App Functionality Groomingsession of EATL-Prothom Alo Apps Contest 2015
  • 2.
    This work islicensed under a Creative Commons Attribution-NonCommercial 4.0 International License. “ First, solve the problem. Then, write the code. ” - John Johnson
  • 3.
    Hello! I am SMAHBUB UZ ZAMAN You can me at mahbub.ninja
  • 4.
    Application Fundamentals Android appsare written in the Java programming language
  • 5.
    “ Activity An activity representsa single screen with a user interface. Service A 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 provider Enable applications to share data Broadcast receiver A 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
  • 6.
  • 7.
    Activity Life Cycle ◦sleep ◦ home button ◦ back button ◦ multitask button ◦ onResume() ◦ onPause()
  • 8.
    @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
  • 10.
  • 11.
    Started or Unbounded Service Thisservice 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
  • 12.
    Broadcast Receiver Broadcast Intentsare used to notify applications of system or application events,
  • 13.
    public class SMSReceiverextends 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); } } }
  • 14.
    <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);
  • 15.
  • 16.
    . Async Task ◦ AsyncTaskenables 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);
  • 17.
    private class DownloadFilesTaskextends 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
  • 18.
    The three typesused 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> {}
  • 19.
    When an asynchronoustask 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
  • 20.
    service or athread ?
  • 21.
    Service A service issimply 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
  • 22.
  • 23.
    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); } @Override public void onCreate(SQLiteDatabase db) { String q = "CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR (255));"; db.execSQL(q); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } SQLiteOpenHelper
  • 24.
    public void addRecord(Stringname) { 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; }
  • 25.
    MyAI db =new MyAI(getApplicationContext()); db.addRecord("A"); db.addRecord("B"); db.addRecord("C"); Log.v("TAG", db.getRecord().toString()); Activity
  • 26.
  • 27.
    Google Map ◦ AddMarker ◦ Mark Path ◦ Shortest Path
  • 28.
  • 29.
  • 31.
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permissionandroid: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
  • 32.
    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>
  • 33.
    public class MainActivityextends 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(); } }
  • 34.
    // latitude andlongitude 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
  • 35.
  • 37.
    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
  • 38.
  • 39.
    ANDROID M DeveloperPreview 1. Permissions 2. Power Improvements (two times longer in standby) 3. USB Type-C will also be supported on Android
  • 40.
  • 41.
    ◦ http://developer.android.com/guide/components/fundamentals.html ◦ http://developer.android.com/reference/android/os/AsyncTask.html ◦http://developer.android.com/guide/components/services.html ◦ https://events.google.com/io2015/ ◦ http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/ ◦ http://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and- cardview-on-android--cms-23465 Resources