/* Create the Intent */
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
/* Fill it with Data */
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"to@email.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text");
/* Send it off to the Activity-Chooser */
context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
I am a very passionate Android application developer. I'll be keep posting here helping resources for fellow Android developers, development issues, new update news from Android and review of Android applications available in the market. So please keep in touch.
I am an Android Developer
Friday, July 16, 2010
Android: Enable and Disable WiFi Programmatically
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);
wifi.setWifiEnabled(enabled);
Android: Recognize Incoming Phone Calls
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.Phone;
import android.telephony.PhoneStateIntentReceiver;
import android.util.Log;
public class ReactOnIncomingCall extends Activity {
/** Used to recognize Messages from the
* myPhoneStateChangedHandler. */
final int PHONECALLSTATE_RECONGNIZE_ID = 0x539;
/** Will notify us on changes to the PhoneState*/
PhoneStateIntentReceiver myPsir = null;
/** This Handler will react on the messages the
* we made our PhoneStateIntentReceiver myPsir
* notify us on. */
Handler myPhoneStateChangedHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// Recognize the Message by its what-ID
if(msg.what == PHONECALLSTATE_RECONGNIZE_ID){
/* Our PhoneStateIntentReceiver myPsir
* now contains some recent data, we can grab. */
Phone.State myState = myPsir.getPhoneState();
// Put the Info to the logger for debugging
Log.d("PhoneCallStateNotified", myState.toString());
if(myState == Phone.State.RINGING){
// Celebrate =D
}
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
// Set some simple layout
super.onCreate(icicle);
setContentView(R.layout.main);
/* Create a new PhoneStateIntentReceiver
* that will pass messages to the handler h
* as it receives Intents we make it notify
* us below*/
this.myPsir = new PhoneStateIntentReceiver(this, myPhoneStateChangedHandler);
/* As we want to get notified on changes
* to the Phones-State we tell our
* PhoneStateIntentReceiver myPsir,
* that we wan to get notified with the ID
* (PHONECALLSTATE_RECONGNIZE_ID) we pass to him
*/
this.myPsir.notifyPhoneCallState(PHONECALLSTATE_RECONGNIZE_ID);
/* Register the Intent with the system. */
this.myPsir.registerIntent();
}
}
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.Phone;
import android.telephony.PhoneStateIntentReceiver;
import android.util.Log;
public class ReactOnIncomingCall extends Activity {
/** Used to recognize Messages from the
* myPhoneStateChangedHandler. */
final int PHONECALLSTATE_RECONGNIZE_ID = 0x539;
/** Will notify us on changes to the PhoneState*/
PhoneStateIntentReceiver myPsir = null;
/** This Handler will react on the messages the
* we made our PhoneStateIntentReceiver myPsir
* notify us on. */
Handler myPhoneStateChangedHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// Recognize the Message by its what-ID
if(msg.what == PHONECALLSTATE_RECONGNIZE_ID){
/* Our PhoneStateIntentReceiver myPsir
* now contains some recent data, we can grab. */
Phone.State myState = myPsir.getPhoneState();
// Put the Info to the logger for debugging
Log.d("PhoneCallStateNotified", myState.toString());
if(myState == Phone.State.RINGING){
// Celebrate =D
}
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
// Set some simple layout
super.onCreate(icicle);
setContentView(R.layout.main);
/* Create a new PhoneStateIntentReceiver
* that will pass messages to the handler h
* as it receives Intents we make it notify
* us below*/
this.myPsir = new PhoneStateIntentReceiver(this, myPhoneStateChangedHandler);
/* As we want to get notified on changes
* to the Phones-State we tell our
* PhoneStateIntentReceiver myPsir,
* that we wan to get notified with the ID
* (PHONECALLSTATE_RECONGNIZE_ID) we pass to him
*/
this.myPsir.notifyPhoneCallState(PHONECALLSTATE_RECONGNIZE_ID);
/* Register the Intent with the system. */
this.myPsir.registerIntent();
}
}
Get Size and Orientation of the Screen of Android Device
/* First, get the Display from the WindowManager */
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
/* Now we can retrieve all display-related infos */
int width = display.getWidth();
int height = display.getHeight();
int orientation = display.getOrientation();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
/* Now we can retrieve all display-related infos */
int width = display.getWidth();
int height = display.getHeight();
int orientation = display.getOrientation();
Android: Vibrate the phone for a given time or a certain pattern
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// 1. Vibrate for 1000 milliseconds
long milliseconds = 1000;
v.vibrate(milliseconds);
// 2. Vibrate in a Pattern with 500ms on, 500ms off for 5 times
long[] pattern = { 500, 300 };
v.vibrate(pattern, 5);
For this to work, you will have to add the android.permission.VIBRATE permission to your Manifest.xml
// 1. Vibrate for 1000 milliseconds
long milliseconds = 1000;
v.vibrate(milliseconds);
// 2. Vibrate in a Pattern with 500ms on, 500ms off for 5 times
long[] pattern = { 500, 300 };
v.vibrate(pattern, 5);
For this to work, you will have to add the android.permission.VIBRATE permission to your Manifest.xml
Android: Get installed Applications with Name, Package Name, Version and Icon
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
log(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode + "\t");
}
}
private void listPackages() {
ArrayList apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i
apps.get(i).prettyPrint();
}
}
private ArrayList getInstalledApps(boolean getSysPackages) {
ArrayList res = new ArrayList();
List packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
log(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode + "\t");
}
}
private void listPackages() {
ArrayList
final int max = apps.size();
for (int i=0; i
apps.get(i).prettyPrint();
}
}
private ArrayList
ArrayList
List
for(int i=0;i
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}
Retrieve JSON from a REST web service
String result = queryRESTurl("http://location/of/wellformed/json.json");
try{
JSONObject json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
Log.i(TAG, "\n" + nameArray.getString(i) + "\n \n" + "\n" + valArray.getString(i) + "\n ");
}
}
catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
public String queryRESTurl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i(TAG, "Result of converstion: [" + result + "]");
instream.close();
return result;
}
} catch (ClientProtocolException e) {
Log.e("REST", "There was a protocol based error", e);
} catch (IOException e) {
Log.e("REST", "There was an IO Stream related error", e);
}
return null;
}
try{
JSONObject json = new JSONObject(result);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
Log.i(TAG, "
}
}
catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
public String queryRESTurl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i(TAG, "Result of converstion: [" + result + "]");
instream.close();
return result;
}
} catch (ClientProtocolException e) {
Log.e("REST", "There was a protocol based error", e);
} catch (IOException e) {
Log.e("REST", "There was an IO Stream related error", e);
}
return null;
}
Phone a telephone number via intent in Android
//Present you with the dialler
Uri telUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_DIAL, telUri);
// Start the call
Uri callUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_CALL, callUri);
Uri telUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_DIAL, telUri);
// Start the call
Uri callUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_CALL, callUri);
How to Make an Activity Fullscreen
public class FullScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
Get the phone's last known location using LocationManager
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
A method to check presence of SD Card in Android device
public static boolean isSdCardPresent() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
Internet Connection Check in Android Devices
Here is how you can check the internet connection in your Android testing device. This works for G1, Hero, Droid etc.
ConnectivityManager mgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if (netInfo != null) {
if (netInfo.isConnected()) {
// do something
} else {
AlertDialog.Builder alertbuilder = new AlertDialog.Builder(
MyActivity.this;
alertbuilder.setTitle("Internet");
alertbuilder.setMessage("Internet is not available");
alertbuilder.setNeutralButton("Ok", okClickListener);
//alertbuilder.setIcon(R.drawable.warning);
alertbuilder.show();
}
} else {
AlertDialog.Builder alertbuilder = new AlertDialog.Builder(
MyActivity.this);
alertbuilder.setTitle("Internet");
alertbuilder.setMessage("Internet is not available");
alertbuilder.setNeutralButton("Ok", okClickListener);
alertbuilder.show();
}
ConnectivityManager mgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if (netInfo != null) {
if (netInfo.isConnected()) {
// do something
} else {
AlertDialog.Builder alertbuilder = new AlertDialog.Builder(
MyActivity.this;
alertbuilder.setTitle("Internet");
alertbuilder.setMessage("Internet is not available");
alertbuilder.setNeutralButton("Ok", okClickListener);
//alertbuilder.setIcon(R.drawable.warning);
alertbuilder.show();
}
} else {
AlertDialog.Builder alertbuilder = new AlertDialog.Builder(
MyActivity.this);
alertbuilder.setTitle("Internet");
alertbuilder.setMessage("Internet is not available");
alertbuilder.setNeutralButton("Ok", okClickListener);
alertbuilder.show();
}
Getting dimension of Android device's screen
If you want the the display dimensions in pixels you can use:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Subscribe to:
Posts (Atom)