Android Cheatsheet For Coders!

As an Android app developer, there are a number of things that you can do. But some help will always come in handy. Each example given below is an example of Context in Android and you can do some nifty things with these. Try them out the next time you sit down with coding for the Android platform on your mind.

Intents

Intents is amongst the most used and best features of Android. They are commonly used to start an Activity, like opening a contact or email, or for starting an Activity for a result, like scanning a barcode or taking a picture to attach it to your mail. You specify intents primarily by using action strings and URIs. In the following code, we use the android.intent.action.VIEW action and the 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 and URI pairs include:

Intent.ACTION_DIAL, tel://8675309
Intent.ACTION_CALL, tel://8675309


You can achieve some other things with startActivityForResult() as well. This can be used to scan a barcode,

Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);


After this, 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");
// ...
}
}


In order to take a picture,

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();
// ...
}
}


Wifi

You can use the WiFiManager in order to enable and disable the WiFi of your device. This is actually quite simple,

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);


Notifications

Text notifications are known as Toast and they appear for a brief period above all other activities. They are also easy to put,

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

The amount of time for displaying the notification can be increased by using Toast.LENGTH_LONG.

Alert and Input Dialogs

An alert is usually used in order to ask the user for an input. You can do this without having to create a new layout. For this use the 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

The LocationManager can be used in order to start up the GPS and then 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());


The LocationManager can also be used in order to find the smartphone’s last known location. This is a faster method than using a LocationListener and then waiting for a fix. Do this by,

// 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

The SmsManager is the one that sends a text.

SmsManager m = SmsManager.getDefault();
String destination = "8675309";
String text = "Hello, Jenny!";
m.sendTextMessage(destination, null, text, null, null);


Vibrate

Vibrating an Android-based smartphone can be done for a specified duation,

(Vibrator) getSystemService(Context.VIBRATOR_SERVICE).vibrate(milliseconds);

Sensors

The SensorManager can be used in order to use the sensor data.

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

The AudioManager can be used in order to enable or disable the silent mode on a smartphone.

mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// or...
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);


Source: Damon Kohler's Blog

Share this

Related Posts

Previous
Next Post »