Sei sulla pagina 1di 8

The following examples are not part of the tutorials but will help you going further.

Android Devices How to make sure the SD card is present?


Sometimes you want to make sure the hardware is there...
if(android.os.Environment.getExternalStorageState().equals(android.os.Environ ment.MEDIA_MOUNTED))

Android Devices How to lock the screen in an Android app?


Remember you need to give permissions for it:

KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE); KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); lock.disableKeyguard();

Android Background processing How to download something in the background in an Android application?
This code fetches content from the web without blocking the UI (runs in the background in a Thread). Once finished, it posts a Handler that is picked up by the UI as soon as possible.
import import import import import java.io.BufferedInputStream; java.io.InputStream; java.net.URL; java.net.URLConnection; org.apache.http.util.ByteArrayBuffer;

public class Iconic extends Activity { private String html = "";

private Handler mHandler; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); checkUpdate.start(); } private Thread checkUpdate = new Thread() { public void run() { try { URL updateURL = new URL("http://iconic.4feets.com/update"); URLConnection conn = updateURL.openConnection(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while((current = bis.read()) != -1){ baf.append((byte)current); } /* Convert the Bytes read to a String. */ html = new String(baf.toByteArray()); mHandler.post(showUpdate); } catch (Exception e) { } } }; private Runnable showUpdate = new Runnable(){ public void run(){ Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show(); } }; }

Android System How to get your application informations?


Want to print what you put in your manifest?
PackageManager manager = this.getPackageManager(); try { PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); String packageName = info.packageName; int versionCode = info.versionCode; String versionName = info.versionName; } catch (NameNotFoundException e) {

// TODO Auto-generated catch block }

Android System How to start an application at bootup?


This snippet starts an Application automatically after the android-os booted up.
<receiver android:enabled="true" android:name=".BootUpReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver> [..] <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> [..] public class BootUpReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, MyActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } }

Android System How to exit an Android application?


do not use System.exit(0); but use: finish() on your activities. If you have multiple activities to close, use startActivityForResult() and pass back a "close now" flag so you know to call finish() on the parent activity as well.

Android System How to uninstall an APK via Intents?


Install an APK
Uri installUri = Uri.fromParts("package", "xxx", null); Intent intent = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri); startActivity(intent);

Android System How to store and retrieve preferences in an Android app?


Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types. It is typically used to store application preferences, such as a default greeting or a text font to be loaded whenever the application is started. Call Context.getSharedPreferences() to read and write values. Assign a name to your set of preferences if you want to share them with other components in the same application, or use Activity.getPreferences() with no name to keep them private to the calling activity. You cannot share preferences across applications (except by using a content provider). This example has been provided by from Here is an example of setting user preferences for silent keypress mode for a calculator:
import android.app.Activity; import android.content.SharedPreferences; public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; . . . @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); }

@Override protected void onStop(){ super.onStop(); // Save user preferences. We need an Editor object to // make changes. All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Don't forget to commit your edits!!! editor.commit(); } }

Android Hardware detection How to programmatically figure out the screen resolution?
This code will give you the screen resolution at run time. The size of your application may differ due to the status and title bar.
@Override public void onCreate(Bundle icicle) { WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); }

Android Display How to display a progress dialog while computing?


This snippet creates a ProgressDialog and a thread to execute something with an unknown duration (web service as an example). When this "thing" finishes, a message is sent to the parent of the thread to stop the ProgessDialog.
final ProgressDialog dialog = ProgressDialog.show(this, "Title",

"Message", true); final Handler handler = new Handler() { public void handleMessage(Message msg) { dialog.dismiss(); } }; Thread checkUpdate = new Thread() { public void run() { // // YOUR LONG CALCULATION (OR OTHER) GOES HERE // handler.sendEmptyMessage(0); } }; checkUpdate.start();

Android Intents How to send an email from an Android application?


Here are two methods using intents. Method one, you want to let the user choose the email client:
Button sendBtn = (Button) findViewById(R.id.send_btn_id); sendBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v){ Intent i = new Intent(Intent.ACTION_SEND); //i.setType("text/plain"); //use this line for testing in the emulator i.setType("message/rfc822") ; // use from live device i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com"}); i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here"); i.putExtra(Intent.EXTRA_TEXT,"body goes here"); startActivity(Intent.createChooser(i, "Select email application.")); } });

and method two, you want to specify a client (NoteToMe here), replace the intent request by:
NoteToMe.this.startActivity(emailIntent); NoteToMe.this.finish();

Android Network How to make sure the network is available?

This function will return true if the network is available, false if it is not (airplane mode, out of reach, etc.). IMPORTANT : Don't forget to add [HTML_REMOVED] in your manifest, or the line NetworkInfo[] info = connectivity.getAllNetworkInfo(); will crash !
public boolean isNetworkAvailable() { Context context = getApplicationContext(); ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { boitealerte(this.getString(R.string.alert),"getSystemService rend null"); } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }

this example has been provided by iznogoud from androidsnippets Network|How to execute a HTTP GET Request with HttpClient? Retrieve the contents of a stream via a HTTP GET.
public static InputStream getInputStreamFromUrl(String url) { InputStream content = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(new HttpGet(url)); content = response.getEntity().getContent(); } catch (Exception e) { Log.("[GET REQUEST]", "Network exception", e); } return content; }

Android Layout fine tuning How to hide the title bar?


Hiding the title bar:
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_PROGRESS);

and to hide the status bar:


getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

Potrebbero piacerti anche