DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Code Gems for Android Developers
refcard cover
Refcard #163

Code Gems for Android Developers

Working with the World's Most Popular Mobile OS

Provides an overview of the API and Tools to develop applications using the Java platform.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Avi Yehuda
Data Developer,
Table of Contents
► What is Android? ► Basic Concepts ► Development ► An Android Project Structure ► User Interface ► System APIs ► Network ► Media (Audio, Video) ► Storage
Section 1

What is Android?

By Avi Yehuda

Android is a stack of operating system, middle ware and applications developed by Google that is dedicated to mobile devices. Android relies on Linux kernel 2.6 for core services. The Android platform provides API and Tools to develop applications using Java Platform. It features Dalvik Virtual Machine, SQLite, an integrated browser, application framework, as well as various media and hardware support.

Section 2

Basic Concepts

The following table outlines the key concepts in an Android application:

Concept

Description

Activity

Activity is the presenter of a single screen in the application. It has certain abilities, like displaying views, menus, alerts and notifications. It can also call another Activity, which means opening a new screen.
Activity is a class that derives from an android.app.Activity.
An application needs to have at least one Activity.
All Activities must be declared in the manifest file.

View

A view is a single user interface element. It handles user events and draws the component on the screen.
Views can contain other Views, these are called view groups.
A View is a class that derives from android.view.View.
There are already many existing views. The developer can use them or create his own customized view by extending any of them.

Intent

Intent is the negotiator between two activities or between two applications. It gives the ability to pass messages and data between the two entities.
When writing applications for mobile, Intent gives access to OS services like opening the camera, a browser, displaying notifications and so on.

Service

A Service is an application that has the ability to run in the background without displaying any user interface.
A Service is a class that derives from android.app.Service.
All Services must be declared in the manifest file.

Section 3

Development

Installing SDK

Download and install the Android SDK
http://developer.android.com/sdk/

Android Development Tools (ADT) Eclipse plugin

Download install and configure ADT for Eclipse.
http://developer.android.com/sdk/eclipse-adt.html

Creating a Project with Eclipse

  • Select File > New > Android Project.
  • Enter Project Name. Press ‘Next’.
  • Select Build Target according to the wanted SDK version. Press ‘Next’.
  • Enter Application name – this is how the user sees the title of your application.
  • Enter Package name – Android demands each application to declare its root package.
  • Create Activity + Activity name.
  • Minimum SDK Version - If you're unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab.
  • Click Finish

Create A PJ

Hot Tip

You can also develop Android applications without Eclipse, but since we are developing in Java, Eclipse makes it easier to develop.

Section 4

An Android Project Structure

Manifest file
AndroidManifest.xml defines the Android application. It contains the attributes, activities, versions, permissions, and other parameters of the application.

'src' folder
As with any Java project, this folder holds all Java source code and packages.

'res' folder
Contains local resources for the application:

  • 'drawable' – image folders according to resolutions. By default there are 3 folders for 3 basic resolutions.
  • 'layout' – xml files which represent display layout. By default a main.xml is created.
  • 'values' – xml files which define global constants, strings, styles or colors.

SDK jar
Contains the android.jar which is different across versions of the SDK.

'gen' folder
This folder contains the R class which is automatically generated by the Eclipse plugin and gives access to the project resources.

'assets' folder
This folder holds other raw resource files such as movie or sound files. By default, this folder is not created. These resources will not be modified.

Creating Android Virtual Device (AVD)

The developer can test his applications on his own device or on an emulator, which comes along with Android SDK.
But first the developer has to define a virtual device that suits his needs.

To create an AVD from Eclipse:

  • Select Window > Android SDK and AVD Manager, or click the Android SDK and AVD Manager icon in the Eclipse toolbar.
  • In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new AVD.
  • Fill in the details for the AVD and click "Create AVD".

AVD

Signing and Generating jars

Android applications are zipped to jar files. The only difference is that Android jar files have a special extension - .apk.
All application jars have to be signed before they are installed.

For more instructions read http://developer.android.com/guide/publishing/app-signing.html

Section 5

User Interface

Android generates user interfaces either from XML or from Java code.

Views

Creating and adding a new View to a Layout in XML

​x
1
<?xml version="1.0" encoding="utf-8"?>
2
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
  android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/mainLayout" >
4
  <TextView 
5
  android:text="My text view" 
6
  android:id="@+id/TextViewExample"
7
​
8
  android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
9
 </LinearLayout>

UI Views

View Groups

A ViewGroupis a special view that can contain other views.

List view

5
1
ListView list = new ListView(this);
2
  String[] listItems = {"Option 1","Option 2","Option 3"};
3
  list.setAdapter(new ArrayAdapter<String>(this,
4
  android.R.layout.simple_list_item_1, listItems ));
5
 list.setOnItemClickListener(new OnItemClickListener() {...

UI List View

Layouts

A Layout is a type of GroupView. It holds views in a certain layout on the screen.

Adding a Layout - XML example - adding to the layout XML

6
1
<?xml version="1.0" encoding="utf-8"?>
2
  <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
3
  android:layout_width="fill_parent" android:layout_height="fill_parent"
4
  android:id="@+id/outer" 
5
  android:orientation="vertical">
6
 </LinearLayout> 

The layout xml is placed in <project_path>/res/layouts

Adding a Layout - Code example
This would be implemented in an Activity class.

4
1
LinearLayout innerLayout = new LinearLayout(this); 
2
  innerLayout.setPadding(20,20,20,20); 
3
  innerLayout.setGravity(Gravity.CENTER);
4
 outerLayout.addView(innerLayout );

Global Strings

A global string, or an array of strings, are declared in an external xml file in the resource folder:<project>/res/values/strings.xml

Declaring a global string

5
1
<?xml version="1.0" encoding="utf-8"?>
2
  <resources>
3
   <string name="hello">Hello World!</string>
4
   <string name="app_name">MyTest</string>
5
 </resources>

Using a global string while creating a TextView

6
1
TextView  
2
   android:layout_width="fill_parent" 
3
   android:layout_height="wrap_content" 
4
   android:text="@string/hello"
5
  />
6
​

Code usage

13
1
String hello = context.getString(R.string.hello); 
2
​
3
  Global String Array
4
  Declaration in a Global String Array 
5
  <?xml version="1.0" encoding="utf-8"?> 
6
  <resources> 
7
  <string-array name="planets_array"> 
8
  <item>Mercury</item> 
9
  <item>Venus</item> 
10
  <item>Earth</item> 
11
   <item>Mars</item> 
12
  </string-array> 
13
 </resources>

Code usage

1
1
String[] planets = context.getResources().getStringArray(R.array.planets_array); 

Menus

Options Menu

An Options menu is presented when the user presses the menu button while the Activity is active.
Step 1 - Creating the menu XML

9
1
<?xml version="1.0" encoding="utf-8"?> 
2
  <menu xmlns:android="http://schemas.android.com/apk/res/android"> 
3
  <item android:id="@+id/new_game" 
4
   android:icon="@drawable/ic_new_game" 
5
  android:title="@string/new_game" /> 
6
  <item android:id="@+id/quit" 
7
  android:icon="@drawable/ic_quit" 
8
   android:title="@string/quit" /> 
9
 </menu>

The layout xml is placed in <project_path>/res/menu

Step 2 – Displaying the menu (implemented in Activity class)

6
1
@Override 
2
  public boolean onCreateOptionsMenu(Menu menu) { 
3
  MenuInflater inflater = getMenuInflater(); 
4
   inflater.inflate(R.menu.game_menu, menu); 
5
  return true; 
6
 } 

Step 3 – Listening to user choice (implemented in Activity class)

14
1
@Override 
2
  public boolean onOptionsItemSelected(MenuItem item) { 
3
   // Handle item selection 
4
  switch (item.getItemId()) { 
5
  case R.id.new_game: 
6
  newGame(); 
7
  return true; 
8
  case R.id.quit: 
9
  quit(); 
10
   return true; 
11
   default: 
12
   return super.onOptionsItemSelected(item); 
13
  } 
14
 } 

Context Menu

A context menu is a floating list of menu items that appears when the user performs a long-press on a View.
Step 1 - Creating a menu XML

9
1
<?xml version="1.0" encoding="utf-8"?> 
2
  <menu xmlns:android="http://schemas.android.com/apk/res/android"> 
3
  <item android:id="@+id/new_game" 
4
   android:icon="@drawable/ic_new_game" 
5
  android:title="@string/new_game" /> 
6
  <item android:id="@+id/quit" 
7
  android:icon="@drawable/ic_quit" 
8
  android:title="@string/quit" /> 
9
 </menu>

Step 2 – Showing the menu (implemented in Activity class)

7
1
@Override
2
  public void onCreateContextMenu(ContextMenu menu, View v,
3
   ContextMenuInfo menuInfo) {
4
  super.onCreateContextMenu(menu, v, menuInfo);
5
  MenuInflater inflater = getMenuInflater();
6
  inflater.inflate(R.menu.context_menu, menu);
7
 }

Step 3 – Listening to user choice (implemented in Activity class)

14
1
@Override
2
  public boolean onContextItemSelected(MenuItem item) {
3
  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
4
  switch (item.getItemId()) {
5
  case R.id.edit:
6
  editNote(info.id);
7
  return true;
8
  case R.id.delete:
9
   deleteNote(info.id);
10
   return true;
11
   default:
12
  return super.onContextItemSelected(item);
13
 }
14
 } 

Step 4 – Attaching the context menu to a view (implemented in Activity class)

1
1
registerForContextMenu(findViewById(R.id.Button01));

Context Menu

Submenu

A submenu is a floating list of menu items that the user opens by pressing a menu item in the Options Menu or a context menu.

14
1
<?xml version="1.0" encoding="utf-8"?> 
2
  <menu xmlns:android="http://schemas.android.com/apk/res/android"> 
3
  <item android:id="@+id/file" 
4
   android:icon="@drawable/file" 
5
   android:title="@string/file" > 
6
  <!-- "file" submenu --> 
7
   <menu> 
8
  <item android:id="@+id/new" 
9
  android:title="@string/new" /> 
10
  <item android:id="@+id/open" 
11
  android:title="@string/open" /> 
12
  </menu> 
13
  </item> 
14
 </menu>

Alerts/Dialogs

Toast
A toast notification is a message that pops up on the surface of the window.

3
1
Toast waitToast = Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG);
2
  waitToast.setGravity(Gravity.TOP, 0, 0);
3
 waitToast.show();

Alerts Dialogs

AlertDialog

15
1
AlertDialog.Builder builder = new AlertDialog.Builder(context); 
2
  builder.setMessage("Are you sure you want to exit?") 
3
  .setCancelable(false) 
4
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
5
  public void onClick(DialogInterface dialog, int id) { 
6
  MyActivity.this.finish(); 
7
   } 
8
   }) 
9
  .setNegativeButton("No", new DialogInterface.OnClickListener() { 
10
  public void onClick(DialogInterface dialog, int id) { 
11
  dialog.cancel(); 
12
   } 
13
  }); 
14
  AlertDialog alert = builder.create(); 
15
 alert.show();

Alert

Status-Bar Notifications

One way to notify an Android user is by displaying notifications in the status bar. You can show a message, play a sound, add an icon and more.

Creating a status bar notification

16
1
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2
  Notification notification = new Notification(R.drawable.icon, "Notification Test", System.currentTimeMillis());
3
  Context context = getApplicationContext();
4
  CharSequence contentTitle = "My notification Title";
5
  CharSequence contentText = "This is the message";
6
  Intent notificationIntent = new Intent(NotificationTest.this, NotificationTest.class);
7
​
8
  //options
9
  notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "4"); //sound
10
  notification.vibrate = new long[]{0,100,200,300}; //vibrate 
11
  //auto cancel after select
12
  notification.flags |= Notification.FLAG_AUTO_CANCEL; 
13
​
14
  PendingIntent contentIntent = PendingIntent.getActivity(NotificationTest.this, 0, notificationIntent, 0);
15
  notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
16
 mNotificationManager.notify(1, notification);

Status Bar

Resource Images

Resource images are placed under <project_dir>/res/drawable

Using a resource image in an image view - XML example

1
1
((ImageView)findViewById(R.id.myImageView)).setImageResource(R.drawable.my_image_name);

Turning the resource image to a Bitmap object

1
1
Bitmap bitmap = BitmapFactory.decodeResource(view.getResources(),R.drawable.my_image_name);

Drawing the bitmap on a canvas object

1
1
canvas.drawBitmap(bitmap, x, y, null);

Creating Links Using Linkfy

Linkfy is a class that lets you create links from TextViews.
You can create links not just to web sites, but to also map addresses, emails and even phone numbers.

Creating web links

3
1
>TextView myWebSite = (TextView) findViewById(R.id.my_web_site); 
2
myWebSite.setText(http://http://www.dzone.com/)
3
Linkify.addLinks(myWebSite , Linkify.WEB_URLS);

Hot Tip

You can also create links to phone numbers, map locations or email addresses.

Using a regular expressionfor filtering strings

5
1
TextView myCustomLink = new TextView(this);
2
  Pattern pattern = Pattern.compile("[a-zA-Z]+&");
3
  myCustomLink.setText("press Linkify& or on Android& to search it on google");
4
  Linkify.addLinks(myCustomLink,pattern, "http://www.google.ie/search?q=");
5
  mainLayout.addView(myCustomLink);
Section 6

System APIs

Using Multithreading for Background Jobs

Regular Thread

7
1
(new Thread(new Runnable() {
2
​
3
  @Override
4
 public void run() {
5
 doLongOperation();
6
 }
7
})).start();

Thread With Handler for UI operations

A new thread cannot update the user interface, so you need to use a handler. The Handler is the middleman between a new thread and the UI message queue.

17
1
final Handler myHandler = new Handler(){
2
  @Override
3
  public void handleMessage(Message msg) {
4
  updateUI((String)msg.obj);
5
  }
6
​
7
  };
8
​
9
  (new Thread(new Runnable() {
10
​
11
  @Override
12
  public void run() {
13
 Message msg = myHandler.obtainMessage(); 
14
msg.obj = doLongOperation();
15
  myHandler.sendMessage(msg);
16
  }
17
 })).start();

Using AsyncTask

An AsyncTask is a thread that can handle user interface operations.

22
1
class MyAsyncTask extends AsyncTask<Integer, String, Long> {
2
@Override
3
  protected Long doInBackground(Integer... params) {
4
long start = System.currentTimeMillis();
5
  for (Integer integer : params) {
6
  publishProgress("start processing "+integer);
7
  doLongOperation();
8
  publishProgress("done processing "+integer);
9
  }
10
return start - System.currentTimeMillis();
11
 }
12
@Override
13
  protected void onProgressUpdate(String... values) {         updateUI(values[0]);  }
14
@Override
15
  protected void onPostExecute(Long time) {
16
  updateUI("Done,it took:"+ time +"millisecondes"); }
17
@Override
18
  protected void onPreExecute() {
19
  updateUI("Starting the process"); }
20
  }
21
MyAsyncTask aTask = new MyAsyncTask();
22
  aTask.execute(1, 2, 3, 4, 5);

Hot Tip

AsyncTask defines 3 generic types: AsyncTask<{type of the input}, {type of the update unit}, {type of the result}>. You don't have to use all of them – simply use 'Void' for any of them.

Using a Timer to Schedule Jobs

A Timer is a comfortable way to dispatch a thread in the future, be it once or more.

6
1
TimerTask timerTask = new TimerTask() {
2
  @Override
3
 public void run() { doSomething(); }
4
}; 
5
Timer timer = new Timer();
6
  timer.schedule(timerTask, 2000,2000);

Opening a new screen

Each screen is a different Activity class. You have to declare each activity in the manifest file.

Opening a new activity

3
1
Intent in = new Intent(myactivity.this, MyActivity2.class);
2
in.putExtra("myKey", "new1"); //passing a parameter
3
startActivity(in);

Receiving a parameter from from the original activity

1
1
String s= getIntent().getExtras().get("myKey").toString()

Going back from the new activity to the original activity

1
1
finish();

Open a new Activity to get theresult

2
1
Intent in = new Intent(myactivity.this, MyActivity2.class);
2
startActivityForResult(in, 0);

Returning a result to the original activity

4
1
Intent in = getIntent();
2
in.putExtra("result", "some parameter");
3
setResult(RESULT_OK,in);
4
finish();

Getting the result from the new activityafter it finishes

2
1
@Override
2
 protected void onActivityResult(int requestCode, int resultCode, Intent data) ...
Section 7

Network

Opening a browser using intent

1
1
startActivity(new Intent(Intent.ACTION_VIEW,  Uri.parse("http://www.dzone.com")));

Enabling Internet permission in the manifest file

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

Reading HTTP using Apache HttpClient

10
1
HttpClient client = new DefaultHttpClient();
2
HttpGet request = new HttpGet();
3
request.setURI(new URI("http://www.dzone.com/"));
4
HttpResponse response = client.execute(request);
5
BufferedReader inBuff = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
6
  String line = null;
7
  while ((line = inBuff.readLine()) != null) {
8
  doSomethingWithHTML(line);        
9
  }
10
  inBuff.close();

Reading a TCP packet using a Socket

5
1
Socket requestSocket = new Socket("remote.servername.com", 13);
2
  InputStreamReader isr = new InputStreamReader(requestSocket.getInputStream(), "ISO-8859-1");
3
  while ((this.ch = isr.read()) != -1) {
4
 myStringBuffer.append((char) this.ch);
5
This may result in following ring formation, where "collin", "owen", and "lisa" are rowkeys.

Embedding a browser inside your application

4
1
WebView  webView = ((WebView)findViewById(R.id.webview));
2
webView.getSettings().setJavaScriptEnabled(true);
3
webView.getSettings().setPluginsEnabled(true); //plugins/flash
4
webView.loadUrl(url);

Loading your own html to the embedded browser

1
1
webView.loadData(htmlString, text/html, utf-8");

Using the system email client

6
1
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
2
  emailIntent.setType("plain/html");    //for html messages
3
  emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"someine@website.com"});
4
  emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "email  Subject");
5
  emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "<H1>email body</H1>");
6
 startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Section 8

Media (Audio, Video)

Using the media player to play local media files

2
1
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); 
2
 mp.start();

Hot Tip

The media files are placed under res/raw

Playing a media file from a path

4
1
MediaPlayer mp = new MediaPlayer();
2
  mp.setDataSource("http://www.somepath.com/file.mp3");
3
  mp.prepare();
4
 mp.start();

Opening the system media player using intent

3
1
Intent intent = new Intent(Intent.ACTION_VIEW);
2
  intent.setDataAndType(Uri.parse( "http://somepath.com/video.mp4" ),"video/mp4");
3
 startActivity(intent);

Displaying video inside your application with VideoView

6
1
getWindow().setFormat(PixelFormat.TRANSLUCENT);
2
  VideoView videoHolder = (VideoView) findViewById(R.id.VideoView01);
3
  videoHolder.setMediaController(new MediaController(this));
4
  videoHolder.setVideoURI(Uri.parse(path+"/"+fileName));
5
  videoHolder.requestFocus();
6
 videoHolder.start();
Section 9

Storage

Storing in shared preferences

Share preferences are a simple key-value storage mechanism of primitive types and Strings. These values are stored even if the program is terminated.

8
1
// Restore preferences
2
SharedPreferences settings = 
3
PreferenceManager.getDefaultSharedPreferences(context) 
4
boolean booleanParam = settings.getBoolean("booleanParam", false); 
5
// Change preferences
6
  SharedPreferences.Editor editor = settings.edit();
7
  editor.putBoolean("booleanParam", true);
8
  editor.commit()

Storing internally
Reading

5
1
int ch;
2
  StringBuilder strContent = new StringBuilder();
3
  FileInputStream fis = openFileInput("my_file");
4
  while ((ch = fis.read()) != -1)
5
 strContent.append((char) ch); 

Writing

4
1
FileOutputStream fop = openFileOutput("my_file", Context.MODE_PRIVATE);  
2
  fop.write("Data to be written".getBytes());
3
  fop.flush();
4
 fop.close(); 

Storing on the SD card

1
1
File path = Environment.getExternalStorageDirectory();

SQLite

Android has a built-in SQLite DB that you can use.

Creating a DB table

5
1
public abstract class DBManager extends SQLiteOpenHelper{
2
public DBManager(Context context,String tableName, String [] columns) {
3
  super(context, "test.db", null, 1);
4
  }
5
  ...

Executing SQL code

1
1
db.execSQL( "create table ..." );

Inserting Data

1
1
getWritableDatabase().insert(tableName, null, values);

GettingData

1
1
getReadableDatabase().query(...);

Camera

Permission in manifest file

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

Launching the Camera using an intent

9
1
private void cameraIntent(){
2
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
3
startActivityForResult(cameraIntent, 1);
4
}
5
@Override
6
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
7
if(data != null && data.getExtras() != null){
8
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
9
  }

Embedding a camera in your application

Step 1-Preview - extending a surface view

23
1
class Preview extends SurfaceView implements SurfaceHolder.Callback{
2
  SurfaceHolder mHolder;
3
Camera mCamera;
4
Preview(Context context) {
5
  super(context);
6
mHolder = getHolder();
7
  mHolder.addCallback(this);
8
  mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
9
  }
10
​
11
  public void surfaceCreated(SurfaceHolder holder) {
12
  mCamera = Camera.open();
13
  mCamera.setPreviewDisplay(holder);
14
  }
15
public void surfaceDestroyed(SurfaceHolder holder) {
16
  mCamera.stopPreview();
17
  mCamera.release();
18
  }
19
​
20
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
21
  mCamera.startPreview();
22
  }
23
 }

Step 2 – Taking pictures

Hot Tip

The camera needs to be in preview mode while taking a picture - otherwise the action will fail
11
1
camera.takePicture(null, null, new PictureCallback() {
2
​
3
  @Override
4
  public void onPictureTaken(byte[] data, Camera camera) {
5
  try{
6
  Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
7
  } finally{
8
  camera.release();
9
  }
10
  }
11
 });

Contacts

Permission in manifest

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

Executing the contacts application using intent

3
1
Intent intent = new Intent(Intent.ACTION_VIEW);
2
  intent.setData(Uri.parse("content://contacts/people/" ));
3
 startActivity(intent);

Using intent to display a contact with id

2
1
Intent intent = new Intent(Intent.ACTION_VIEW);
2
 intent.setData(Uri.parse("content://contacts/people/"+id )); startActivity(intent); 

Phone calls

Permission in manifest

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

Execute a phone call

3
1
Intent intent = new Intent(Intent.ACTION_CALL);
2
  intent.setData(Uri.parse("tel:+436641234567"));
3
 startActivity(intent); 

Call a contact

3
1
Intent intent = new Intent(Intent.ACTION_CALL);
2
  intent.setData(Uri.parse("content://contacts/people/"+contact_id));
3
 startActivity(intent);

Display the dialer with a number

3
1
Intent intent = new Intent(Intent.ACTION_DIAL);
2
  intent.setData(Uri.parse("tel:+436641234567"));
3
 startActivity(intent);

SMS, MMS

Permission in manifest file

2
1
uses-permission android:name="android.permission.SEND_SMS">
2
 /uses-permission>

Open SMS application

4
1
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
2
  sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
3
  sendIntent.setType("vnd.android-dir/mms-sms");
4
 startActivity(sendIntent);

Open MMS application

7
1
:Intent sendIntent = new Intent(Intent.ACTION_SEND); 
2
sendIntent.putExtra("sms_body", "additional text");
3
//attaching an image
4
  File img = new File("/sdcard/a.png");
5
  sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(img));   
6
  sendIntent.setType("image/png");
7
  startActivity(sendIntent); 

Send SMS from your code

4
1
PendingIntent pi = PendingIntent.getActivity(this, 0, 
2
  new Intent(this, this.getClass()), 0) 
3
  SmsManager sms = SmsManager.getDefault();
4
 sms.sendTextMessage(phoneNumber, null, message, pi, null); 

Geo-location

Required permission in manifest file

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

Listening to user location updates

Location updates are received from GPS, Network or Passive (other applications' data).

11
1
LocationManager locationManager = 
2
 (LocationManager) context.getSystemService(LOCATION_SERVICE);
3
LocationListener myLocationListener = new LocationListener() {
4
  ...
5
  };
6
locationManager.requestLocationUpdates(
7
   LocationManager.NETWORK_PROVIDER, 0, 0, myLocationListener);
8
  locationManager.requestLocationUpdates(
9
   LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
10
  locationManager.requestLocationUpdates(
11
   LocationManager.PASSIVE_PROVIDER, 0, 0, myLocationListener);

Fetching Screen Properties

9
1
Display display = getWindowManager().getDefaultDisplay();
2
int screenHeight = display.getHeight();
3
int screenWidth = display.getWidth();
4
int orientation = getResources().getConfiguration().orientation;
5
  if (orientation == Configuration.ORIENTATION_PORTRAIT) {
6
 // portrait
7
  } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
8
 // Landscape
9
  }

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

SQLiteOpenHelper and Database Inspector in Android
related article thumbnail

DZone Article

Realm by Example: CRUD on Android in 200 Lines of (Very Readable) Java
related article thumbnail

DZone Article

Storing Objects in Android
related article thumbnail

DZone Article

How to Convert XLS to XLSX in Java
related refcard thumbnail

Free DZone Refcard

Swift Essentials
related refcard thumbnail

Free DZone Refcard

Mobile Web Application Testing
related refcard thumbnail

Free DZone Refcard

Getting Started With PhoneGap
related refcard thumbnail

Free DZone Refcard

HTML5 Mobile Development

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: