Tuesday, June 12, 2012

Android: SharedPreferences shared by different activities

Following code cannot be shared by different Activities:

context.getSharedPreferences("PreferenceManager", context.MODE_PRIVATE).getString(key, defaultValue);

If you save on one Activity and wants to load on the other activity, the other Activity cannot find it.

Solution:
PreferenceManager.getDefaultSharedPreferences(context).getString(key, defaultValue);

Monday, June 11, 2012

Domain: How to register your domain to search engine?



Domain: How to promote your website to search engines? (for free)

iNeedHits - iNeedHits

Submit Express - Submit Express

DreamSubmit - DreamSubmit

Android: How to get device unique ID example

Available starting from 2.3+ (level 9)

  public void example() {
         String sUID = Build.SERIAL;
  }

Android: Get device model name example


  public void example() {
         String sModel = Build.MODEL;
  }

Android: Get device CPU Processor example


  public void example() {
         String sCPU = Build.CPU_ABI;
  }

Android: Get device manufacturer name example


  public void example() {
         String sManufacturer = Build.MANUFACTURER;
  }

Android: Get Android OS version example

  public void example() {
         String sOSVersion = Build.VERSION.RELEASE;
  }

Android: Wifi - Get hidden SSID example


       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String hiddenSSID = wifiInfo.getHiddenSSID();

Android: wifi - Get Network Link Speed exmaple


       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String networkSpeed = wifiInfo.getLinkSpeed();

Android: Wifi - Get network ID exmaple


       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String networkId = wifiInfo.getNetworkId();

Android: Wifi Get RSSI example

       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String rssi = wifiInfo.getRssi();

Android: wifi get BSSID example


       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String bssid = wifiInfo.getBSSID();

Android: Wifi Get SSID example


       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String ssid = wifiInfo.getSSID();

Android: Wifi get MAC address example


       WifiManager wifiManager = (WifiManager)
                    getSystemService(Context.WIFI_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       String sMac = wifiInfo.getMacAddress();

Android: wifi Get IMEI example


TelephonyManager
tManager = (TelephonyManager)
             getSystemService(Context.TELEPHONY_SERVICE);
return tManager.getDeviceId();

Android: Wifi get IP address example

String ipAddress = "";
try {
       for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
             NetworkInterface intf = en.nextElement();
             for (Enumeration<InetAddress> enumIpAddr = intf
                           .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                           ipAddress = inetAddress.getHostAddress().toString();
                    }
             }
       }
} catch (SocketException ex) {
}

Android: Check if wifi is enabled and/or connected example

             ConnectivityManager conMan = (ConnectivityManager)
                           getSystemService(Context.CONNECTIVITY_SERVICE);

             //mobile
             State mobile = conMan.getNetworkInfo(0).getState();

             //wifi
             State wifi = conMan.getNetworkInfo(1).getState();

             if (mobile == NetworkInfo.State.CONNECTED
                           || mobile == NetworkInfo.State.CONNECTING) {
                 //mobile
             } else if (wifi == NetworkInfo.State.CONNECTED
                           || wifi == NetworkInfo.State.CONNECTING) {
                 //wifi
             }

Android: Run linux command example

Runtime.getRuntime().exec()

For example, change chmod of a file:

             Process process = null;
             try {
                    process = Runtime.getRuntime().exec("su -c chmod 0777 file");
                    process.waitFor();
             } catch (Exception e) {
                    return false;
             }
             finally {
                    try {
                           process.destroy();
                    } catch (Exception e) {
                    }
             }
            return true;

Android: Screen lock source code (Locks the screen to turn on)

AndroidManifest.xml
    <uses-permission android:name="android.permission.WAKE_LOCK" />
Source:
       private PowerManager.WakeLock mWLock;

       @Override
       protected void onStart() {
             super.onStart();
             try {
                    PowerManager pm =
                                  (PowerManager)getSystemService(Context.POWER_SERVICE);
                    mWLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                                 | PowerManager.FULL_WAKE_LOCK
                                 | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Lock Name");
                    mWLock.acquire();
             } catch(Exception e) {
                    Log.e("ScreenLock", "onStart()::acquire() failed " + e.toString());
             }
       }

       @Override
       protected void onStop() {
             try {
                    mWLock.release();
            } catch(Exception e) {}
     }

Android: Get Power status (if device is plugged in)

(From Activity)

public boolean getPowerStatus() {
        Intent intent = this.registerReceiver(null,
                    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int isConnected = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return isConnected == BatteryManager.BATTERY_PLUGGED_AC ||
                    isConnected == BatteryManager.BATTERY_PLUGGED_USB;
    }

Wednesday, May 9, 2012

Android: Manifest accelerate Hardware &

android:largeHeap="true"

=> Increase application memory heap. more
android:hardwareAccelerated="true"

=> Accelerate the hardware.
=> However, it limits the size of texture. For example, Bitmap cannot load bigger than 2048x2048.
      see here

Android: (Memory Management) memory leak - free ImageView resource

In order to free ImageView/Drawable object to gain memory space:

        ImageView v = (ImageView) _________;
        ((BitmapDrawable) v.getDrawable()).setCallback(null);
        

Usually you do it on onDestroy()

private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
        ((ViewGroup) view).removeAllViews();
    }
}


For Bitmap, you use recycle().

Android: (Memory Management) code dump hprof file


android.os.Debug.dumpHprofData("/sdcard/heapdump.hprof");

Android: (Memory Management) How to interpret D/dalvikvm log

D/dalvikvm log is shown in the Log whenever GC happens.

Reason for GC
D/dalvikvm( 9050): GC_CONCURRENT freed 2049k, 65% free 3571K/ 9991K, external 4703K/5261K, paused 2ms+2ms

Reason for GC:
- GC_CONCURRENT : heap has been mostly filled up, so GC runs before heap is full.
- GC_FOR_MALLOC : heap is entirely filled up, we had to STOP and GC.
- GC_EXTERNAL_ALLOC : (Won't see this in Honeycomb+) Bitmap are externally allocated momory.
- GC_HPROF_DUMP_HEAP
- GC_EXPLICIT : called when you call 'System.gc()';

Amount freed
D/dalvikvm( 9050): GC_CONCURRENT freed 2049k, 65% free 3571K/ 9991K, external 4703K/5261K, paused 2ms+2ms

External Memory Information
D/dalvikvm( 9050): GC_CONCURRENT freed 2049k, 65% free 3571K/ 9991K, external 4703K/5261K, paused 2ms+2ms

(amount of external memory your app has allocated)/(Soft limit)

Pause Time
D/dalvikvm( 9050): GC_CONCURRENT freed 2049k, 65% free 3571K/ 9991K, external 4703K/5261K, paused 2ms+2ms

(beginning pause) + (during pause)

Android: (Memory Management) Larger Heap size

To make lager heap:

 <application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:hardwareAccelerated="true">

Warning:
- Larger heap size means longer GC(Garbage Collection) time.
- If you make your app heap size bigger, it will significantly slow down other apps and users will soon know your app is the problem.
- Don't use this option just because you get memory error.

To check heap size on your device:

  ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
  int memoryClass = am.getMemoryClass();
  int memoryClass2 = am.getLargeMemoryClass();
  Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass) + " large: " + memoryClass2);

Wednesday, April 25, 2012

Android: Load bitmap from SD Card

       String fileSavePath = Environment.getExternalStorageDirectory() + "abc.png";
       Bitmap bitmap = BitmapFactory.decodeFile(fileSavePath);
       ImageView imageView = (ImageView)findViewById(R.id.imageview);
       imageView.setImageBitmap(bitmap);

Monday, April 16, 2012

Android: UI thread example

Some cases cannot be ran on a thread processor such as Updating UI.
In this case, you run on UI Thread:

             new Thread() {
                    @Override
                    public void run() {
                           try {
                                 // code runs in a thread
                                 activity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                               // code runs in a UI(main) thread
                                        }
                                 });
                           } catch (final Exception ex) {
                           }
                    }
             }.start();

To make this easier (or harder in some cases), there's AsyncTask.

Android: new thread example

Simple example:

        new Thread() {
            @Override
            public void run() {
                try {
                    // do something useful
                } catch (Exception e) {
                   
                }
            }
        }.start();

Or use AsyncTask

Android: Open browser with link example

You simply call a new Intent with URL link like following:


    public void openBrowser(final String link) {
       if(link.contains("http")) {
             Intent i = new Intent(Intent.ACTION_VIEW);
             i.setData(Uri.parse(link));
             startActivity(i);
       }
    }


Friday, April 13, 2012

Android: How to refresh on transparent background webview?

If you set Webview's background to be transparent, then whenever you load a new page, contents will overlap.

To solve this issue:


       webView.clearView();
       webView.loadUrl(url);

Clear view before you load something else.

Thursday, April 12, 2012

Android Webview with transparent background

Yes, it is possible!

           webView.setBackgroundColor(0x00FFFFFF);

However, if in your AndroidManifest.xml contains:

             android:hardwareAccelerated="true"
webView's background, for some reason, does not change to transparency.
(It took me while to figure this out!)

This is how to disable hardware acceleration on the view that contains webview:

             view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Wednesday, April 11, 2012

Android facebook api: what is Android Key Hash?

When registering Facebook App, it requires you to type 'Android Key Hash'.
How to get Android Key Hash?







4 Prerequisites:
1. Must have Eclipse installed and android sdk installed
2. Locate 'debug.keystore' : usally at - C:\Users\(user name)\.android\debug.keystore
3. Locate 'keytool.exe' : usally at - C:\Program Files\Java\jre6 (your version)\bin
4. Open ssl: for 32 bit: here , for 64 bit: here.
    Extract to : C:\openssl










Now..

Type: keytool -exportcert -alias androiddebugkey -keystore C:\Users\Joshua\.android\debug.keystore | C:\openssl\bin\openssl sha1 -binary | C:\openssl\bin\openssl base64






type: 'android' for the password

That it!!

Monday, April 9, 2012

Android EditText set cursor position to end

Set cursor to end:

        EditText editText = (EditText)findViewById(R.id.edit_text);
        editText.setSelection(editText.getText().length());

Set cursor to front:
        EditText editText = (EditText)findViewById(R.id.edit_text);
        editText.setSelection(0);

Android Dialog with default width

Having trouble making Dialog width to default length? (At least curtain length)

Use MinWidth theme:

final Dialog dialog = new Dialog(this, android.R.style.Theme_Holo_Dialog_MinWidth);
dialog.setContentView(R.layout.main);
dialog.setCancelable(true);
dialog.show();

You can also use: android.R.style.Theme_Holo_Light_Dialog_MinWidth

Android Dialog with transparent background

This is an example of when an Activity is set as Dialog style:

Ex:
AndroidManifest.xml:

        <activity
            android:theme="@android:style/Theme.Holo.Light.Dialog.MinWidth"
            android:name=".DialogActivity" />

Different Dialog styles are:
- android:theme="@android:style/Theme.Dialog"
- android:theme="@android:style/Theme.Holo.Dialog"
- android:theme="@android:style/Theme.Holo.Dialog.MinWidth"
- android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"
- android:theme="@android:style/Theme.Holo.Dialog.NoActionBar.MinWidth"
- android:theme="@android:style/Theme.Holo.DialogWhenLarge"
- android:theme="@android:style/Theme.Holo.DialogWhenLarge.NoActionBar"
- android:theme="@android:style/Theme.Holo.Light.Dialog"
- android:theme="@android:style/Theme.Holo.Light.Dialog.MinWidth"
- android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar"
- android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar.MinWidth"
- android:theme="@android:style/Theme.Holo.Light.DialogWhenLarge"
- android:theme="@android:style/Theme.Holo.Light.DialogWhenLarge.NoActionBar"

DialogActivity.java:

       @Override
       protected void onCreate(Bundle savedInstanceState){
             super.onCreate(savedInstanceState);
             requestWindowFeature(Window.FEATURE_NO_TITLE);
             getWindow().setBackgroundDrawable(new ColorDrawable(0));
             setContentView(R.layout.main);
       }

-------------------------------------

OR:

Dialog:


             final Dialog dialog = new Dialog(this, android.R.style.Theme_Holo_Light_Dialog_MinWidth);
             dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
             dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
             dialog.setContentView(R.layout.main);
             dialog.setCancelable(true);
             dialog.show();