tech talk: app functionality (android)
TRANSCRIPT
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0
International License.
“ First, solve the problem. Then, write the code. ” - John Johnson
“
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
@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
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
◦ 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
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
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
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
<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
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.htmlhttps://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
◦ 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