Sunday, December 5, 2010

Check for Updates in background Once in two days - schedule a background updates checker

This code checks for updates of the Activity once in 2 days and in the background. If an update (higher version than current) is found, it opens a Dialog and asks the user to open the market. 

code-snippet:-
public class Test extends Activity {
    private Handler mHandler;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.front);
        mHandler = new Handler();
       
        /* Get Last Update Time from Preferences */
        SharedPreferences prefs = getPreferences(0);
        lastUpdateTime =  prefs.getLong("lastUpdateTime", 0);
       
        /* Should Activity Check for Updates Now? once in 2days */
        if ((lastUpdateTime + (2*24 * 60 * 60 * 1000)) < System.currentTimeMillis()) {

            /* Save current timestamp for next Check*/
            lastUpdateTime = System.currentTimeMillis();           
            SharedPreferences.Editor editor = getPreferences(0).edit();
            editor.putLong("lastUpdateTime", lastUpdateTime);
            editor.commit();       

            /* Start Update */           
            checkUpdate.start();
        }
    }
   
    /* This Thread checks for Updates in the Background */
    private Thread checkUpdate = new Thread() {
        public void run() {
            try {
                URL updateURL = new URL("http://abc.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. */
                final String s = new String(baf.toByteArray());        
               
                /* Get current Version Number */
                int curVersion = getPackageManager().getPackageInfo("your.application.id", 0).versionCode;
                int newVersion = Integer.valueOf(s);
               
                /* Is a higher version than the current already out? */
                if (newVersion > curVersion) {
                    /* Post a Handler for the UI to pick up and open the Dialog */
                    mHandler.post(showUpdate);
                }               
            } catch (Exception e) {
            }
        }
    };

    /* This Runnable creates a Dialog and asks the user to open the Market */
    private Runnable showUpdate = new Runnable(){
           public void run(){
            new AlertDialog.Builder(Test.this)
            .setIcon(R.drawable.icon)
            .setTitle("Update Available")
            .setMessage("An update for is available!\n\nOpen Android Market and see the details?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked OK so do some stuff */
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:your.application.id"));
                            startActivity(intent);
                    }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked Cancel */
                    }
            })
            .show();
           }
    };   
}


To check if SD Card is present on android device via code

To check if SD Card is present on the device, we can use simple code
public static boolean isSdCardPresent(){
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);  

 

Wednesday, November 10, 2010

Obtain IP Address for android device

Two ways to find the device ip:-

1. Method1:-  Open a socket to a known website/webserver like google.com or yahoo.com and get the ip using the technique shown below. It is straight forward(but not recommended)
String get_ip(){
java.net.Socket conn = null;
String ipAddress;

try {
conn = new java.net.Socket("www.google.com", 80);
} catch (UnknownHostException unknownhostexception) {
unknownhostexception.printStackTrace();
} catch (IOException ioexception) {
ioexception.printStackTrace();

ipAddress = conn.getLocalAddress().toString();
Toast.makeText(ip.this," Device IP --"+ipAddress,Toast.LENGTH_LONG).show();
return ipAddress;
}
2. Method2:- Iterate over all network interfaces and iterate there over all ip addresses. (Recommended way)

public String getLocalIpAddress() {

try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();}}}
} catch (SocketException exception) {
Log.e("We got Exception here", exception.toString());
}
return null;
}

Note:- This will give you simple way to get the ip address (For device on WiFi we need to access wifiManager class) and is independent of Android. This is generic java code and can be used on the laptop as well


Hope it helps!

Saturday, September 4, 2010

Harsha Bhogle at IIMA

Android figures

An overview about the Android SDK


1. The Android SDK was announced officially on November 12, 2007.

2. Table showing various Android versions and API levels

3.  The Latest version of Android SDK is 2.2 called as Froyo

4.  Android had a 2.8% share of the worldwide smartphone market. By the following quarter (Q3 2009),
     Android’s market share had grown to 3.5%.

5.  Android would become the world’s second most popular smartphone platform. while BlackBerry falls
    from 2nd to 5th place. iPhone remains in 3rd place. Microsoft’s Windows Mobile remains in 4th place.

Sunday, July 11, 2010

Android Handler

Message Handler
I have started looking into Android.

I have tried to build a utility class that can do Network I/O. And grasping things was little hard at first. Network I/O or other heavy-duty stuff in Android should be done on other worker thread. Because doing it in main thread (or the UI thread) can ( and will ) make your application unresponsive and may be killed as the system is persuaded to think that it has hung. For every Android developer, this is a must-read.

So you have to do the long running operations in separate thread. And to interact between threads you have to resort to Handler. A Handler is used to send message or runnable to a particular thread. The thing to remember is that a Handler is associated with the MessageQueue of the single thread which has created it. After creating a Handler, it can be used to post message or runnable to that particular thread.

Here is an example

--------------------------------------------------------------------------------
  1. public class MyActivity extends Activity {

    void startHeavyDutyStuff() {

    // Here is the heavy-duty thread
    Thread t = new Thread() {

    public void run() {
    while (true) {

    mResults = doSomethingExpensive();

    //Send update to the main thread
    messageHandler.sendMessage(Message.obtain(messageHandler, mResults)); }}};
    t.start();
    }

    // Instantiating the Handler associated with the main thread.
    private Handler messageHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
    switch(msg.what) {
    //handle update
    //.....}}};}
--------------------------------------------------------------------------------

Friday, December 4, 2009

Dial a number from App

Code snippet to dial a number from app:-

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class DialANumber extends Activity {
EditText mEditText_number = null;
LinearLayout mLinearLayout_no_button = null;
Button mButton_dial = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mLinearLayout_no_button = new LinearLayout(this);

mEditText_number = new EditText(this);
mEditText_number.setText("5551222");
mLinearLayout_no_button.addView(mEditText_number);

mButton_dial = new Button(this);
mButton_dial.setText("Dial!");
mLinearLayout_no_button.addView(mButton_dial);
mButton_dial.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
performDial();
}
});

setContentView(mLinearLayout_no_button);
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CALL) {
performDial();
return true;
}
return false;
}

public void performDial(){
if(mEditText_number!=null){
try {
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mEditText_number.getText())));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}