Friday, June 26, 2009

Android SDK code snippets





Button init/listener

Button btn1 = (Button)findViewById(R.id.btn1); //locates it from xml file


btn1.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ btn1_method(); }}); //calls btn1_method() method
Simple short duration message a.k.a toast
public static void toaster(Context context, String message, int length){
  //Toast.LENGTH_SHORT or Toast.LENGTH_LONG


  Toast.makeText(context, message, length).show();
}
Send sms/text message
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
public static void sms(String to, String text){
  SmsManager.getDefault().sendTextMessage(to, null, text, null, null);
}
Get lat/longitude
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation("gps");
tvLat.setText("init lat: "+Double.toString(loc.getLatitude()));
tvLong.setText("init long: "+Double.toString(loc.getLongitude()));


No comments: