2011年9月28日 星期三

[Android] Dynamically change Options Menu Items in Android

Sometimes, we need to change options menu dynamically, you can follow this example.
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		// You can use mEnableMenu to enable meun
		if (mEnableMenu)
		{
			menu.add(0, 0, 0, "Setting");
		}
		return super.onPrepareOptionsMenu(menu);
	}

Reference: 

[Android] How to monitor sdcard mount/unmout?

In this example, we demo the sdcard mount/unmount monitor.
	public void onCreate() {
		super.onCreate();
		this.registerReceiver(this.myReceiver, getSDCardIntentFilter());
	}

	public IntentFilter getSDCardIntentFilter() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		intentFilter.addDataScheme("file");
		return intentFilter;
	}

	private BroadcastReceiver myReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) 
		{
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED))
			{
			  // handle SD card unmounted
			}
			else if (action.equals(Intent.ACTION_MEDIA_MOUNTED))
			{
			  // handle SD card mounted
			}
		}
	};

[Android] How to block back and search button on Dialog?

It will cancel dialog If user press back or search button on dialog. Therefore, sometimes we need to block back and search button on dialog to ensure the logic of dialog can work normally.
		public void alertDialog(final String title, final String msg, final String btn1, final String btn2, final String btn3, final String cmd, final String data)
		{
			AlertDialog.Builder MyAlertDialog = new AlertDialog.Builder(self);
			MyAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
			MyAlertDialog.setTitle(title);
			MyAlertDialog.setMessage(msg);
			MyAlertDialog.setCancelable(false); // block back button

			MyAlertDialog.setOnKeyListener(new DialogInterface.OnKeyListener()
			{
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
				{
					if (keyCode==KeyEvent.KEYCODE_SEARCH)	// block search button
						return true;
					else
						return false;
				}
			});

			DialogInterface.OnClickListener OkClick = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				// Handle onClick
				}
			};
			if (btn1 != null)
				MyAlertDialog.setPositiveButton(btn1, OkClick );
			if (btn2 != null)
				MyAlertDialog.setNegativeButton(btn2, OkClick );
			if (btn3 != null)
				MyAlertDialog.setNeutralButton(btn3, OkClick );

			 MyAlertDialog.show();
		}

[Android] How to create status bar notification?

To create a status bar notification:


1. Get a reference to the NotificationManager:
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

2. Instantiate the Notification:
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

3. Define the Notification's expanded message and Intent:
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

4. Pass the Notification to the NotificationManager:
private static final int HELLO_ID = 1;

mNotificationManager.notify(HELLO_ID, notification);
That's it. Your user has now been notified.

Reference:

2011年9月16日 星期五

[Android] How can I refresh MediaStore on Android?

Sometimes, we cannot get the correct information from MediaStore after file add or delete. We need to do MediaStore refresh to make MediaStore parsing the information instantly.
package com.roryok.MediaRescan;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

public class MediaRescan extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory()))); 
        setContentView(R.layout.main);
    }

    //Rescan the sdcard after copy the file
    private void rescanSdcard() throws Exception{     
      Intent scanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory()));   
      IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
      intentFilter.addDataScheme("file");     
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));    
    }
}


Reference:

2011年9月2日 星期五

[JavaScript] How to format string?

String.format = function(src){
  if (arguments.length == 0) 
    return null;

  var args = Array.prototype.slice.call(arguments, 1);
  return src.replace(/\{(\d+)\}/g, function(m, i)
  {
    return args[i];
  });
};

Demo:
msg will be "This is variable A and variable B.

var template = "This is variable {0} and variable {1}";
var variable1 = "A";
var variable2 = "B";
var msg = String.format(template, variable1, variable2);

[Java] How to check if a directory is not empty?

This is a example to demo how to check if a directory is not empty?

package org.kodejava.example.io;

import java.io.File;

public class EmptyDirCheck {
    public static void main(String[] args) {
        File file = new File("/home/username/data");

        //
        // Check to see if the object represent a directory.
        //
        if (file.isDirectory()) {
            //
            // Get list of file in the directory. When its length is not zero
            // the folder is not empty.
            //
            String[] files = file.list();

            if (files.length > 0) {
                System.out.println("The " + file.getPath() + " is not empty!");
            }
        }
    }
}

Reference: