Monday, June 11, 2012

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);