Tuesday, December 18, 2012

Convert Seconds into HH:MM:SS in java?

Below are the methods to convert seconds into minute seconds format...


int day = (int)TimeUnit.SECONDS.toDays(seconds);      
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
 System.out.println("Random Element "+minute+":"+second);

OR 

public static void calculateTime(long seconds) {
   int day = (int) TimeUnit.SECONDS.toDays(seconds);
   long hours = TimeUnit.SECONDS.toHours(seconds) -
                TimeUnit.DAYS.toHours(day);
   long minute = TimeUnit.SECONDS.toMinutes(seconds) -
                 TimeUnit.DAYS.toMinutes(day) -
                 TimeUnit.HOURS.toMinutes(hours);
   long second = TimeUnit.SECONDS.toSeconds(seconds) -
                 TimeUnit.DAYS.toSeconds(day) -
                 TimeUnit.HOURS.toSeconds(hours) -
                 TimeUnit.MINUTES.toSeconds(minute);
   System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}

Monday, December 10, 2012

Android serialization of Objects ?


We can also see below links...
http://www.dreamincode.net/forums/topic/248522-serialization-in-android/

I'm going to go through the process of serializing and deserializing an object.

What this means is that we're going to convert an object into an array of bytes, which can easily be moved around or stored (for later use). And for deserialization we just take those bytes and convert them back into an Object.

The first one we have below is the serialization method, which just takes in a generic Object.


  public static byte[] serializeObject(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      ObjectOutput out = new ObjectOutputStream(bos);
      out.writeObject(o);
      out.close();

      // Get the bytes of the serialized object
      byte[] buf = bos.toByteArray();

      return buf;
    } catch(IOException ioe) {
      Log.e("serializeObject", "error", ioe);

      return null;
    }
  }

The second one is the deserialization method, which takes in an array of bytes;


  public static Object deserializeObject(byte[] b) {
    try {
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
      Object object = in.readObject();
      in.close();

      return object;
    } catch(ClassNotFoundException cnfe) {
      Log.e("deserializeObject", "class not found error", cnfe);

      return null;
    } catch(IOException ioe) {
      Log.e("deserializeObject", "io error", ioe);

      return null;
    }
  }

If you're wondering how to use these, well here is an example.


  public class Bla implements Serializable {
    public String blaDate;
    public String blaText;
  }
 
  Bla bla = new Bla();
 
  // assuming that both those serialize and deserialize methods are under the SerializerClass
  byte[] blaBytes = SerializerClass.serializeObject(bla);
 
  Bla deserializedBla = (Bla) SerializerClass.deserializeObject(blaBytes);

You've probably noticed that I implemented Serializable - you need this in order to serialize an object. Some of the built in objects already have this implemented - for example the ArrayList object.

When deserializing you need to cast it back to what the object was, since it's returning it as a generic Object - hence the (Bla).
Anyways, hope this helped someone, and if you noticed any mistakes, please let me know.

Thursday, November 22, 2012

Resource Folder Content ?


Check this link http://developer.android.com/training/multiscreen/index.html
http://developer.android.com/guide/practices/screens_support.html
http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html
http://jayxie.com/mirrors/android-sdk/resources/samples/MultiResolution/index.html
http://tools.android.com/recent/dealingwithdependenciesinandroidprojects
http://developer.android.com/about/dashboards/index.html

Taken from Here

In the /res folder you can have:

anim/ - XML files that define tween animations

color/ - XML files that define a state list of colors.

drawable/ - Bitmap files / Nine-Patches (re-sizable bitmaps) / State lists / Shapes / Animation drawables / Other drawables

layout/ - XML files that define a user interface layout.

menu/ - XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.

raw/ - Arbitrary files to save in their raw form.

values/ - XML files that contain simple values, such as strings, integers, and colors.

arrays.xml for resource arrays (typed arrays).
colors.xml for color values
dimens.xml for dimension values.
strings.xml for string values.
styles.xml for styles.
xml/ - Arbitrary XML files

Also see Accessing Alternative Resources for more specific device configurations (locale, dpi, size, aspect, orientation, etc



Also We can have value folder like : -

res/values-ldpi/dimens.xml
res/values-mdpi/dimens.xml
res/values-hdpi/dimens.xml
res/values-sw720dp/dimens.xml

Drawable folders can be of : -

xhdpi: 720x1280
large-hdpi: 640x960
hdpi: 480x640
mdpi: 320x480
ldpi: 240x320

res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)



The size ratios should match the nominal pixel densities as Android defines them:

ldpi - 120 pixels/inch; dpi scale = .75 (4 dpi = 3 pixels)
mdpi - 160 pixels/inch; dpi scale = 1 (1 dpi = 1 pixel)
hdpi - 240 pixels/inch; dpi scale = 1.5 (2 dpi = 3 pixels)
xhdpi - 320 pixels/inch; dpi scale = 2 (1 dpi = 2 pixels)

So if you make your xhdpi images twice the size (in pixels) of the mdpi resources, they will be the same dpi, meaning they will be the same physical size on their respective screens.








Thursday, November 1, 2012

How to show dialog yes/No before leaving the app via Back button ?



private boolean isLastActivity() {
   final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningTaskInfo> tasksInfo = am.getRunningTasks(1024);

    final String ourAppPackageName = getPackageName();
    RunningTaskInfo taskInfo;
    final int size = tasksInfo.size();
    for (int i = 0; i < size; i++) {
        taskInfo = tasksInfo.get(i);
        if (ourAppPackageName.equals(taskInfo.baseActivity.getPackageName())) {
            return taskInfo.numActivities == 1;
        }
    }

    return false;
}

You wil also require below permission in manifest....

<uses-permission android:name="android.permission.GET_TASKS" />

Thus in your Activty you can just use the following:

public void onBackPressed() {
    if (isLastActivity()) {
         showDialog(DIALOG_EXIT_CONFIRMATION_ID);
    } else {
         super.onBackPressed(); // this will actually finish the Activity
    }
}

Wednesday, October 17, 2012

List Chart API ?

How to view the android.jar source code in eclipse?



This plugin helps you to add source to android libraries in Eclipse.

In ADT >=8.0.0 you can add Android sources to Android container for all your project with installing the Android source feature using...

http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/

After downloading the com.android.ide.eclipse.source_16.0.0.201112171909.jar file in plugin folder, unzip it.We will get the below sources for the following API levels:

14 - Android 4.0.1
10 - Android 2.3.4
9 - Android 2.3
8 - Android 2.2
7 - Android 2.1
6 - Android 2.0.1
4 - Android 1.6
3 - Android 1.5

The plugin is about 240 MB size.

Each folder will contain the sources.zip file within it.Copy zip file from "10" folder and paste it into below path of corresponding version...

android-sdk-linux/platform/android-10/"paste here"

i.e sources.zip and android.jar both file will be in same folder.

Now restart you eclipse and browse to android.jar file,now you can view the source code....


How to restart service with AlarmManager ?

Supposed you are running the below service......We just need to register and unregister the alarm,in service lifecycle.



package com.example.differentlayout;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

class PersistentService extends Service {

private static final String TAG = "PersistentService";

// support persistent of Service
void registerRestartAlarm() {
Log.d(TAG, "registerRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 10 * 1000; // 10 seconds after the alarm event occurs
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,10 * 1000, sender);
}

void unregisterRestartAlarm() {
Log.d(TAG, "unregisterRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(sender);
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
unregisterRestartAlarm();
super.onCreate();
}

@Override
public void onDestroy() {
registerRestartAlarm();
super.onDestroy();
}

}



Write the receiver which wake ups our above service....


package com.example.differentlayout;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class RestartService extends BroadcastReceiver {
 public static final String ACTION_RESTART_PERSISTENTSERVICE = "ACTION.Restart.PersistentService";

@Override
 public void onReceive(Context context, Intent intent) {
   Log.d("RestartService", "RestartService called!@!@@@@@#$@$@#$@#$@#");
   if(intent.getAction().equals(ACTION_RESTART_PERSISTENTSERVICE)) {
     Intent i = new Intent(context, PersistentService.class);
     context.startService(i);
 }
}
}


In manifest file don't forgot to mention the RestartService as remote.....


<receiver android:name="RestartService" android:process=":remote">
       <intent-filter>
                       <action android:name="ACTION.Restart.PersistentService"></action>
        </intent-filter>
</receiver>