Skip to main content

Android Recipes and Snippets

I've put together a small collection of Android recipes. For each of these recipes, this is an instance of Context (more specifically, Activity or Service) unless otherwise noted. Enjoy :)

Intents
One of the coolest things about Android is Intents. The two most common uses of Intents are starting an Activity (open an email, contact, etc.) and starting an Activity for a result (scan a barcode, take a picture to attach to an email, etc.). Intents are specified primarily using action strings and URIs. Here are some things you can do with the android.intent.action.VIEW action and startActivity().
Intent intent = new Intent(Intent.ACTION_VIEW);
// Choose a value for uri from the following.
// Search Google Maps: geo:0,0?q=query
// Show contacts: content://contacts/people
// Show a URL: http://www.google.com
intent.setData(Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Other useful action/URI pairs include:
  • Intent.ACTION_DIAL, tel://8675309
  • Intent.ACTION_CALL, tel://8675309
More interesting things are available when you use startActivityForResult(). For example, to scan a barcode:
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
Then, add onActivityResult to your activity.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
Bundle extras = data.getExtras();
String result = extras.getStringExtra("SCAN_RESULT");
// ...
}
}
Taking a picture is done like so:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
// ...

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
Check out the OpenIntents registry for more information.

Wifi

The WifiManager can be used to enable and disable wifi. Where enabled is a boolean, it's as easy as:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);
Notifications
Text notifications (called Toast) which appear briefly above all activities are also easy:
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
You can increase the time the notification is displayed by using Toast.LENGTH_LONG instead.

Alert and Input Dialogs
Sometimes it's useful to prompt the user for input. An easy way to do that without creating a new layout is to use AlertDialog.Builder.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(title);
alert.setMessage(message);

// You can set an EditText view to get user input besides
// which button was pressed.
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});

alert.show();
Location
Use the LocationManager to start up the GPS and listen for location updates.
LocationManager locator = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
location.getAltitude();
location.getLatitude();
location.getLongitude();
location.getTime();
location.getAccuracy();
location.getSpeed();
location.getProvider();
}
}

public void onProviderDisabled(String provider) {
// ...
}

public void onProviderEnabled(String provider) {
// ...
}

public void onStatusChanged(String provider, int status, Bundle extras) {
// ...
}
};

// You need to specify a Criteria for picking the location data source.
// The criteria can include power requirements.
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // Faster, no GPS fix.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix.
// You can specify the time and distance between location updates.
// Both are useful for reducing power requirements.
mLocationManager.requestLocationUpdates(mLocationManager.getBestProvider(criteria, true),
MIN_LOCATION_UPDATE_TIME, MIN_LOCATION_UPDATE_DISTANCE, mLocationListener,
getMainLooper());
You can also get the phone's last known location using the LocationManager. This is faster than setting up a LocationListener and waiting for a fix.
// Start with fine location.
Location l = locator.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (l == null) {
// Fall back to coarse location.
l = locator.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
SMS
Sending a text is done with the SmsManager.
SmsManager m = SmsManager.getDefault();
String destination = "8675309";
String text = "Hello, Jenny!";
m.sendTextMessage(destination, null, text, null, null);
Vibrate
You can vibrate the phone for a specified duration like so:
(Vibrator) getSystemService(Context.VIBRATOR_SERVICE).vibrate(milliseconds);
Sensors
Accessing sensor data is done using the SensorManager.
SensorManager mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
private final SensorListener mSensorListener = new SensorListener() {
public void onAccuracyChanged(int sensor, int accuracy) {
// ...
}

public void onSensorChanged(int sensor, float[] values) {
switch (sensor) {
case SensorManager.SENSOR_ORIENTATION:
float azimuth = values[0];
float pitch = values[1];
float roll = values[2];
break;
case SensorManager.SENSOR_ACCELEROMETER:
float xforce = values[0];
float yforce = values[1];
float zforce = values[2];
break;
case SensorManager.SENSOR_MAGNETIC_FIELD:
float xmag = values[0];
float ymag = values[1];
float zmag = values[2];
break;
}
}
};

// Start listening to all sensors.
mSensorManager.registerListener(mSensorListener, mSensorManager.getSensors());
// ...
// Stop listening to sensors.
mSensorManager.unregisterListener(mSensorListener);
Silence Ringer
You can use the AudioManager to enable and disable silent mode.
mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// or...
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Useful Links
That's it from me for now. But, here are some useful sources of more information:

Popular posts from this blog

Bot Commander r1 Released

I just published Bot Commander , the code for my Lego NXT rover . There's a lot left to be done, but release early and often, right? Currently it provides a UI for controlling the direction and speed of all three motor ports on the NXT brick. You can link motors together to adjust their speed in unison. In addition, you can enable "Tilt Control" for a steering-wheel-type experience. To use tilt control: Hook up motor A and B to be the left and right wheels of your vehicle. Hold the phone sideways (i.e. landscape). Tilt the phone forward and backward to drive forward and backward. Turn the phone right and left (like a steering wheel) to steer right and left. As you tilt the phone, you'll see the UI update the slider controls for the speed of motors A and B. I plan to expand the UI to provide a lot more than just motor control. Before that, though, I'll push a JAR to make it easy to integrate control of Lego NXT robots into your own Android project. The code
Read more

Email Injection

Not so long ago, I ran a wiki called SecurePHP. On that wiki, there was one particular article about email injection that received a lot of attention. Naturally, with all the attention came lots of spam. As a result, I disabled editing of the wiki and content stagnated. Still, the email injection article remained popular. About a year later, the server that hosted SecurePHP died and I never had a chance to hook it all back up. I saved the article though and I'm reposting it now. It may be a bit old (I've been away from PHP for a long time), and I didn't write all of it, so feel free to leave comments about needed updates and corrections. Though this article focuses on PHP, it provides a lot of general information regarding email injection attacks. The PHP mail() Function There are a lot of ways to send anonymous emails, some use it to mass mail, some use it to spoof identity, and some (a few) use it to send email anonymously. Usually a web mailform using the mail() funct
Read more