Friday, July 27, 2012

How to save application state while orientation in Android ?


You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
}

The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}

You'd usually use this technique to store instance values for your application (selections, unsaved text, etc.).

Thursday, July 26, 2012

Download Java Plugin in Chrome Ubuntu?


Install ubuntu-restricted-extras, which will install openjdk (an open source version of Java) from the terminal with following command....

sudo apt-get install ubuntu-restricted-extras

It takes quite a while, but it'll install most of the plugins and codecs most people use.

Wednesday, July 25, 2012

How to delete a directory(recursively) in Android ?


Just call the below method from anyWhere in the code and just pass the file parameter address eg..

File a=new File("sdcard/example/com");
a.deleteDir(a);


This will call below method and delete the "com" directory...

public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}


OR


void recursiveDelete (File dirPath) {
String [] ls = dirPath.list ();
for (int idx = 0; idx < ls.length; idx++) {
File file = new File (dirPath, ls [idx]);
if (file.isDirectory ())
recursiveDelete (file);
file.delete ();

}
}

Tuesday, July 24, 2012

How to Upload Zip File through SOAP in Android?



Below is class File which uploads the zip file...




import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class UploadWebservice extends Activity {
private static String SOAP_ACTION = "http://tempuri.org/";
private static String METHOD_NAME = "";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://192.168.100.114/Webservice/Service1.asmx";
static HashMap<String, String> propertiesMap;
private static boolean isUploadSuccessfull;
//private static final String SOAP_ACTION = "http://tempuri.org/ITransferService/UploadFile";
 //private static final String SOAP_ACTION = "\"http://tempuri.org/ITransferService/UploadFile\"";

private static int incrementBy=0;
static Handler handler;
static Dialog downloadProgressdialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

propertiesMap = new HashMap<String,String>();
METHOD_NAME = "";
METHOD_NAME = "UploadLog";
SOAP_ACTION = "http://tempuri.org/";
SOAP_ACTION = SOAP_ACTION+METHOD_NAME;
propertiesMap.put("emailid","shuklaxyz@yahoo.com");
propertiesMap.put("password","abc");
propertiesMap.put("FileName","abc.zip");
propertiesMap.put("FolderName","Shailesh");

Call();


handler = new Handler() {


public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
LayoutInflater factory = LayoutInflater.from(UploadWebservice.this);          
final View progressDialogView = factory.inflate(R.layout.progressbar, null);
TextView progressTV =  (TextView)progressDialogView.findViewById(R.id.progressbarpercentagetxt);
ProgressBar downloadProgressBar = (ProgressBar)progressDialogView.findViewById(R.id.progress_bar);


incrementBy =incrementBy+total/2;
downloadProgressBar.setMax(total);
downloadProgressBar.incrementProgressBy(incrementBy);
if(incrementBy<total)
progressTV.setText(Integer.toString((incrementBy*100)/total)+"% Completed");
else{
downloadProgressBar.setProgress(total);
progressTV.setText("100% Completed");
}
downloadProgressdialog.setContentView(progressDialogView);
downloadProgressdialog.show();

if(downloadProgressBar.getProgress() == downloadProgressBar.getMax()){
System.out.println("Completed upload");
downloadProgressdialog.dismiss();
incrementBy = 0;

if(isUploadSuccessfull){
AlertDialog.Builder adb=new AlertDialog.Builder(UploadWebservice.this);
adb.setTitle("guideVue");
adb.setMessage("Logs Uploaded Successfully.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

}

});

adb.show();
}else{
AlertDialog.Builder adb=new AlertDialog.Builder(UploadWebservice.this);
adb.setTitle("guideVue");
adb.setMessage("Problem occured while uploading,Please try again later.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

}

});

adb.show();
}
}

}
};

}




public static void Call() {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Iterator<String> ite = propertiesMap.keySet().iterator();
while (ite.hasNext()) {
String key = (String) ite.next();
String value = (String) propertiesMap.get(key);
request.addProperty(key, value);
System.out.println("Kye|Value:" + key + "|" + value);
}

String log_zipFile="sdcard/a/b/abc.zip";
final byte[] bytebuffer = convertToByteArray(new File(log_zipFile));
System.out.println("***ByteBuffer:" + bytebuffer.length);

Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", bytebuffer.length);
msg.setData(b);

request.addProperty("logsbuffer", bytebuffer/*
* Base64.encode(bytebuffer,
* Base64.DEFAULT)
*/);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

MarshalBase64 marshal = new MarshalBase64();
marshal.register(envelope);
System.out.println("Webservice URL UploadLog:" + URL + METHOD_NAME);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
SoapPrimitive result = null;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
result = (SoapPrimitive) envelope.getResponse();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


System.out.println("Webservice Result UploadLog:" + result.toString());
isUploadSuccessfull = Boolean.parseBoolean(result.toString());
if (log_zipFile.endsWith(".zip"))
new File(log_zipFile).delete();
}

private static byte[] convertToByteArray(final File file) {
   if (file.isDirectory())
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is a directory");
   if (file.length() > Integer.MAX_VALUE)
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is too big");

   Throwable pending = null;
   FileInputStream in = null;
   final byte buffer[] = new byte[(int) file.length()];
   try {
       in = new FileInputStream(file);
       in.read(buffer);
   } catch (Exception e) {
       pending = new RuntimeException("Exception occured on reading file "
                       + file.getAbsolutePath(), e);
   } finally {
       if (in != null) {
               try {
                       in.close();
               } catch (Exception e) {
                       if (pending == null) {
                               pending = new RuntimeException(
                                       "Exception occured on closing file"
                            + file.getAbsolutePath(), e);
                       }
               }
       }
       if (pending != null) {
               throw new RuntimeException(pending);
       }
   }
   return buffer;
}

}






Below is the progressbar.xml for Showing Progress Dialog.......


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="15px" >

    <TextView
        android:id="@+id/progressbartxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Please wait..." />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10px" />

    <TextView
        android:id="@+id/progressbarpercentagetxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="0% Completed" />

</LinearLayout>









Monday, July 23, 2012

How to record video in android app?



import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class OpenCamera extends Activity {
private static int REQUEST_VIDEO_CAPTURED = 2;
Uri uriVideo = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_screen);
Button b = (Button) findViewById(R.id.btn_end);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 120);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_VIDEO_CAPTURED) {
uriVideo = data.getData();

if (uriVideo != null) {
Log.e("---------VIDEO PATH", uriVideo.getPath().toString());

String videoPath = convertMediaUriToPath(uriVideo);

//you can move the file to desired location
String targetPath = "sdcard/a/b/c/";
File sourceFile = new File(videoPath);
String targetDir = targetPath;
// Move file to new directory
String sourceFileName = sourceFile.getName();

/*
* For renaming the file String new_File1 =
* String.valueOf(System.currentTimeMillis() ); String new_File
* = fileName.substring(0, fileName.indexOf(".")) +
* new_File1+".3gp";
*/

boolean success = sourceFile.renameTo(new File(targetDir,sourceFileName));
if (!success) {
// File was not successfully moved
System.out.println("not Succesful");
}
System.out.println("File move Successfully");
}
}
}

protected String convertMediaUriToPath(Uri uri) {
String path=null;
   String [] proj={MediaStore.Images.Media.DATA};
   Cursor cursor = getContentResolver().query(uri, proj,  null, null, null);
   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
 
   if(cursor.getCount()!=0){
    cursor.moveToFirst();
    path = cursor.getString(column_index);
   }
   cursor.close();
   return path;
}

}

Get the file into ByteArray in Android ?


private byte[] convertToByteArray(final File file) {
   if (file.isDirectory())
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is a directory");
   if (file.length() > Integer.MAX_VALUE)
       throw new RuntimeException("Unsupported operation, file "
                       + file.getAbsolutePath() + " is too big");

   Throwable pending = null;
   FileInputStream in = null;
   final byte buffer[] = new byte[(int) file.length()];
   try {
       in = new FileInputStream(file);
       in.read(buffer);
   } catch (Exception e) {
       pending = new RuntimeException("Exception occured on reading file "
                       + file.getAbsolutePath(), e);
   } finally {
       if (in != null) {
               try {
                       in.close();
               } catch (Exception e) {
                       if (pending == null) {
                               pending = new RuntimeException(
                                       "Exception occured on closing file"
                            + file.getAbsolutePath(), e);
                       }
               }
       }
       if (pending != null) {
               throw new RuntimeException(pending);
       }
   }
   return buffer;
}

Sunday, July 22, 2012

Get the color of a specific pixel Java Android example ?


ImputStream      is = this.getResources().openRawResource(R.drawable.colors);
Bitmap    mBitmap2 = BitmapFactory.decodeStream(is);

int  w = mBitmap2.getWidth();
int  h = mBitmap2.getHeight();
//  int x , y have to be smaller as w , h
int _color =  mBitmap2.getPixel(x, y);

Get Screen Size Pixels per Inch Android example ?


The exact physical pixels per inch of the screen,Get size of pixel,Get DPI,Get count of pixels per inch

float mXDpi;
float mYDpi;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mXDpi = metrics.xdpi; // The exact physical pixels per inch of the screen in the X dimension.
 mYDpi = metrics.ydpi;
float  mMetersToPixelsX = mXDpi / 0.0254f; // 1 inch == 0.0254 metre
float  mMetersToPixelsY = mYDpi / 0.0254f;

configChanges value of the com.google.ads.AdActivity must include ?


Errors:

E/Ads(333): The android:configChanges value of the com.google.ads.AdActivity must include screenLayout.
E/Ads(333): The android:configChanges value of the com.google.ads.AdActivity must include uiMode.
E/Ads(333): The android:configChanges value of the com.google.ads.AdActivity must include screenSize.
E/Ads(333): The android:configChanges value of the com.google.ads.AdActivity must include smallestScreenSize.
E/Ads(333): You must have AdActivity declared in AndroidManifest.xml with configChanges.

Solution:
Try to using a lower version of the GoogleAdMobAdsSDK ADS SDK in project:
GoogleAdMobAdsSDK-4.0.4.jar


Add activity to AndroidManifest.xml

// .............. blah
    <uses-sdk android:minSdkVersion="4"/>
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application android:icon="@drawable/dicts_ico" android:label="@string/app_name"
    >
           <meta-data
        android:value="a12345_your_number"
        android:name="ADMOB_PUBLISHER_ID" />
        <activity android:name=".MainStartMenu"
                  android:label="@string/app_name"
                  android:configChanges="keyboardHidden|orientation"
                  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


  <!-- Google ads -->    
<activity android:name="com.google.ads.AdActivity"
              android:configChanges="keyboard|keyboardHidden|orientation"/>

// ......... blah

Warning: android.support.v4 ProGuard ?



Problem:

Warning: android.support.v4.view.accessibility.AccessibilityRecordCompatIcs: can't find referenced class android.view.accessibility.AccessibilityRecord
Warning: android.support.v4.widget.EdgeEffectCompatIcs: can't find referenced class android.widget.EdgeEffect

Solution:

Try to insert into proguard.cfg or into ${sdk.dir}/tools/proguard/proguard-android.txt (by version Android SDK) this line

-dontwarn android.support.**

Thursday, July 19, 2012

Why override tostring method in java ?




The toString() method in the Object class is used to display some information regarding any object.
If any code needs some information of an object of a class, then it can get it by using this method

The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.


package com.example.generics;

public class ToStringMethodTest {
private String companyName;
private String companyAddress;
public ToStringMethodTest(String companyName, String companyAddress) {
this.companyName = companyName;
this.companyAddress = companyAddress;
}
public static void main(String[] args) {
ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
System.out.println(test.toString());
}

public String toString() {
return ("Company Name: " + companyName + "n" +
"Company Address: " + companyAddress);
}
  }

OUTPUT:

Company Name: ABC private LtdnCompany Address: 10, yy Street, CC Town

But if you comment the toString() method...you will get output below

com.example.generics.ToStringMethodTest@9304b1


What we have just now seen is just a sample of how a meaningful override of the toString() method would prove to be of great use in displaying an object’s information when we try printing an object using the System.out.println statement during debugging processs.

How to open .chm file in ubuntu?


To open a .chm file in linux, you can use the package xchm.

To install xchm run the command

sudo apt-get install xchm

or open the synaptic package manager, and search for xchm.
Then right click mark for installation-> apply->apply.

Once this is done, you will be able to see the xchm in
Applications-->office-->xCHM.

Cick on the xCHM, it will open the xCHM apllication.
Click on "open" on the top  and then browse to the location where you have kept your .chm file, select it and click on open.

You .chm file should open now.

Wednesday, July 18, 2012

Timer in Android ?



Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:
CountDownTimer waitTimer=new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();


to stop the timer early we can call:

     if(waitTimer != null) {
         waitTimer.cancel();
         waitTimer = null;
     }

Sunday, July 15, 2012

Get drawable Id based on string Android?


here is a code snippet on how to do it:


public static int getDrawable(Context context, String name)
{
Assert.assertNotNull(context);
Assert.assertNotNull(name);

return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}

Force android check for update OTA?


Your android phone is programmed to check for update every X hours, but you can force this check by doing this:

1 open your phone dialer
2 insert this number *#*#2432546#*#* this mean *#*#checkin#*#*
3 If every thing went ok, you will see an exclamation icon in your notification bar, and if you have an update pending you should be notified.

String concatenation with double quotes?

StringBuffer strbuf = new StringBuffer();

String inputType ="Textbox";
String selectedRadio = "";
String inputAppendID = "123";


strbuf.append("<Input ID=\"" + inputAppendID +"\" "+ " Type=\""+ inputType +"\" "+ ">" + "<Option SelectedItem=\""+ selectedRadio +"\" "+ "/>" + "</Input>");

Tuesday, July 10, 2012

Android – Task Manager Primitive Prototype





Setup The Android Manifest With The “Android.Permission.GET_TASKS” Permission

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.apache.hello">
    <uses-permission id="android.permission.GET_TASKS"/>
    <application>
        <activity class=".HelloApp" android:label="HelloApp">
            <intent-filter>
                <action android:value="android.intent.action.MAIN" />
                <category android:value="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Code A Simple ListActivity

package org.apache.hello;


import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class HelloApp extends ListActivity {


    final IActivityManager manager = ActivityManagerNative.getDefault();


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


        updateTaskList();


        this.getListView().setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView adapterview, View view, int i, long l) {
                try {
                    manager.moveTaskToFront(i);
                } catch (DeadObjectException e) {
                    Log.e("HelloApp", e.getMessage(), e);
                }
            }


            public void onNothingSelected(AdapterView adapterview) {
            }
        });
    }


    public void onWindowFocusChanged(boolean flag) {
        updateTaskList();
    }


    private void updateTaskList() {
        ArrayList items = new ArrayList();
        try {
            List tasks = manager.getTasks(10, 0, null);
            int i = 1;
            for (Iterator iterator = tasks.iterator(); iterator.hasNext();) {
                IActivityManager.TaskInfo item = (IActivityManager.TaskInfo) iterator.next();
                items.add(new String((i++) + " : " + item.baseActivity.getPackageName()));
            }
        } catch (DeadObjectException e) {
            Log.e("HelloApp", e.getMessage(), e);
        }
        setListAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, items));
    }
}

Get active Application name in Android ?


ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while(i.hasNext()) {
  ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
  try {
    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
    Log.w("LABEL", c.toString());
  }catch(Exception e) {
    //Name Not FOund Exception
  }
}

Android - binding to the Music app service to find currently playing song ?


For an Android app I’m working on I need to find out what song, if any, is playing in the background on the device. Turns out there’s no documented way to do this on Android - but it also turns out that using an open source platform is great. After a few hours of poking around I had a working proof of concept, and I’m sure someone more familiar with Android would’ve figured it out much faster.

IMPORTANT: I’m using an undocumented interface. While this works on Android 1.5R3 and T-Mobile G1 (HTC Magic), and likely on other versions/devices, there is no guarantee it’ll keep working in future releases - use at your own risk.


The default way to play music on the G1 is the Music app. Since it can play music in the background, it seemed likely there is some way to interact with the service it uses. This of course doesn’t help if the user is using some other music player, but it should be good enough.

First step was to figure out exactly what service that is - I used something like the following code to find out what services are running while I’m playing music:

ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);


List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);


for (int i=0; i<rs.size(); i++) {
ActivityManager.RunningServiceInfo rsi = rs.get(i);
Log.i("Service", "Process " + rsi.process + " with component " + rsi.service.getClassName());
}

This prints up to 50 running services. The interesting line in the output is

process com.android.music with component com.android.music.MediaPlaybackService

OK, now to figure out how to interact with MediaPlaybackService. It turns out to be surprisingly simple.

First, get a copy of IMediaPlaybackService.aidl from the source code of the Music app, and include it in your Android app. The contents of this file are the methods we have access to in MediaPlaybackService. Of course, if the Music app on the device changes, and our copy of the .aidl file is inaccurate, we have a problem - hence the warning above.

Next, implement a ServiceConnection we can use to connect to MediaPlaybackService.

private class MediaPlayerServiceConnection implements ServiceConnection {


public IMediaPlaybackService mService;


public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("MediaPlayerServiceConnection", "Connected! Name: " + name.getClassName());


// This is the important line
mService = IMediaPlaybackService.Stub.asInterface(service);


// If all went well, now we can use the interface
try {
Log.i("MediaPlayerServiceConnection", "Playing track: " + mService.getTrackName());
Log.i("MediaPlayerServiceConnection", "By artist: " + mService.getArtistName());
if (mService.isPlaying()) {
Log.i("MediaPlayerServiceConnection", "Music player is playing.");
} else {
Log.i("MediaPlayerServiceConnection", "Music player is not playing.");
}
} catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e);
}
}


public void onServiceDisconnected(ComponentName name) {
Log.i("MediaPlayerServiceConnection", "Disconnected!");
}
}

Finally, bind the service:

Intent i = new Intent();
i.setClassName("com.android.music", "com.android.music.MediaPlaybackService");
ServiceConnection conn = new MediaPlayerServiceConnection();
this.bindService(i, conn, 0);

That’s it! From here on it should be possible to use the MediaPlaybackService like any other service.

Android: check if a service is running ?


The App I am working on consists of a background service, which continuously posts and checks data and a couple of activities. In the activity I would like to give the user possibility to toggle the related service on and off. But how do I know if my service is currently running or not?

After checking different approaches I eventually got to the following compact and reliable solution. From inside an activity:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.MyService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

This works reliably because it is based on the information about running services provided by the Android operating system through ActivityManager#getRunningServices.

All the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill you process or which of the mentioned callbacks are called or not. Please note the “killable” column in the lifecycle events table in Android documentation.

Monday, July 9, 2012

Google Map API key genaration in ubuntu for Android?


shailesh@shailesh-desktop:~$  cd /
shailesh@shailesh-desktop:/$ cd usr/
shailesh@shailesh-desktop:/usr$ cd lib/
shailesh@shailesh-desktop:/usr/lib$ cd jvm/
shailesh@shailesh-desktop:/usr/lib/jvm$ cd java-6-openjdk/
shailesh@shailesh-desktop:/usr/lib/jvm/java-6-openjdk$ cd bin/

then we want to get the keystore.To get the android default debug keystore:

eclipse->windows->preferences->Android ->Build, then copy the  default debug keystore.

eg: /home/shailesh/.android/debug.keystore \

shailesh@shailesh-desktop:/usr/lib/jvm/java-6-openjdk/bin$ keytool -list -alias androiddebugkey \-keystore /home/shailesh/.android/debug.keystore \
> -storepass android -keypass android
androiddebugkey, 11 Jun, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5): 65:13:5E:81:B6:F4:99:12:8C:0C:4A:DF:60:3B:48:B8

shailesh@shailesh-desktop:/usr/lib/jvm/java-6-openjdk/bin$


Then take the following link: https://developers.google.com/android/maps-api-signup
Then agree the teams and conditions to generate key.

Your key is:
0vU_TfSqyKwFGQzFx08B4SLzVDTy62tVto_0CYA

This key is good for all apps signed with your certificate whose fingerprint is:
65:13:5E:81:B6:F4:99:12:8C:0C:4A:DF:60:3B:48:B8

What is the Difference between Service, Async Task & Thread?



Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components.

I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.

Sunday, July 8, 2012

What is the difference between callbacks and listeners?



Callback. The other code tells the developer: Hey, if this event occurs, I'll call the function in this bucket. You must know where the bucket is to connect your callback.

Listeners. The other code tells the developer: Hey, if this thing occurs, I'll send this event. You can connect your handler (hopefully) where it makes sense to you.

Explanation 1:


A callback is procedure you pass as an argument to another procedure. The procedure receiving the parameter can call it, or share it so some other procedures in the system can call it.

An event handler is a procedure called when an event happens. It can be a callback.
An event handler is a type of callback. It's called whenever an event occurs. The term is usually used in terms of user interfaces where events are things like moving the mouse, clicking something and so on.

Explanation 2:


A listener watches for an event to be fired. For example, a KeyListener waits for KeyEvents, a MessageListener waits for messages to arrive on a queue and so on.

The handler is responsible for dealing with the event. Normally, listeners and handlers go hand-in-hand. For example, the KeyListener tells the ExitHandler that "the letter Q was pressed" and the handler performs logic such as cleaning up resources and exiting the application gracefully. Similary a ButtonClickListener would tell the same ExitHandler that the "Exit button was clicked". So, in this case you have two different events, two different listeners but a single handler.

Explanation 3:


A listener is an object that listens, (and takes actions) upon certain events. I.e. it "listens" for events. Cf. the observer pattern.
Example: The MouseListener in the Java API.

A handler is an object that handles certain things that the client class don't want to deal with. I.e. it "handles" events. A typical scenario is that I provide a handler for a specific event/task as an argument to a constructor.
Example: The MemoryHandler in the Java API.

A concrete difference would be that you can have multiple listeners (just call addXxxxListener several times) while you're only supposed to have a single handler.


Friday, July 6, 2012

How to get decimal HTML entity from String in Java?



Below is the method for returning the decimal entity.........

public static String getHTMLEntity(String value) {
StringBuffer testBuffer = new StringBuffer();
char[] test = value.toCharArray();
if (test != null) {
int size1 = test.length;


for (int j = 0; j < size1; j++) {
testBuffer.append("&#");
testBuffer.append(Character.codePointAt(test, j));
testBuffer.append(";");
}
}
return testBuffer.toString();
}


OUTPUT for "सड्फलक्ल क्लजकलसदफ  à¤•्ळज्सलड्फ"


&#2360;&#2337;&#2381;&#2347;&#2354;&#2325;&#2381;&#2354;&#32;&#2325;&#2381;&#2354;&#2332;&#2325;&#2354;&#2360;&#2342;&#2347;&#32;&#32;&#2325;&#2381;&#2355;&#2332;&#2381;&#2360;&#2354;&#2337;&#2381;&#2347;

How to print text from string of HTML decimal entity in Java?


Below is the Code..........


String encodeString="&#2360;&#2337;&#2381;&#2347;&#2354;&#2325;&#2381;&#2354;&#32;&#2325;&#2381;&#2354;&#2332;&#2325;&#2354;&#2360;&#2342;&#2347;&#32;&#32;&#2325;&#2381;&#2355;&#2332;&#2381;&#2360;&#2354;&#2337;&#2381;&#2347;";



 StringBuffer sb = new StringBuffer();
   Matcher m = Pattern.compile("\\&#(\\d+);").matcher(s);
   while (m.find()) {
       int uc = Integer.parseInt(m.group(1));
       m.appendReplacement(sb, "");
       sb.appendCodePoint(uc);
   }
   m.appendTail(sb);



System.out.print(sb.toString());


OUTPUT :
सड्फलक्ल क्लजकलसदफ  à¤•्ळज्सलड्फ

How to get unicode characters from String ?


Below is the Example.....

StringBuffer a = new StringBuffer();
try {
String line = "Shailesh Shukla";
for (int index = 0; index < line.length(); index++) {
String hexCode = Integer.toHexString(line.codePointAt(index))
.toUpperCase();
String hexCodeWithAllLeadingZeros = "0000" + hexCode;
String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros
.substring(hexCodeWithAllLeadingZeros.length() - 4);
a.append("\\u" + hexCodeWithLeadingZeros + " ");
}
} catch (Exception e) {
}
System.out.println(a.toString());

OUTPUT For String "Shailesh Shukla"

\u0053 \u0068 \u0061 \u0069 \u006C \u0065 \u0073 \u0068 \u0020 \u0053 \u0068 \u0075 \u006B \u006C \u0061 

Monday, July 2, 2012

Create an object from a string in Java?

import java.lang.reflect.*;

Class [] classParm = null;
Object [] objectParm = null;

try {
    String name = "com.rgagnon.MyClass";
    Class cl = Class.forName(name);
    java.lang.reflect.Constructor co = cl.getConstructor(classParm);
    return co.newInstance(objectParm);
}
catch (Exception e) {
    e.printStackTrace();
    return null;
}



Another example, but this time we are passing a parameter to the //constructor and calling a method dynamically.

public class Test {
    public static void main(String args[]) {
        
        try {
            String name = "java.lang.String";
            String methodName = "toLowerCase";
            
            // get String Class
            Class cl = Class.forName(name);
            
            // get the constructor with one parameter
            java.lang.reflect.Constructor constructor =cl.getConstructor(new Class[] {String.class});
            
            // create an instance
            Object invoker =constructor.newInstance (new Object[]{"REAL'S HOWTO"});
            
            // the method has no argument
            Class  arguments[] = new Class[] { };
            
            // get the method
            java.lang.reflect.Method objMethod = cl.getMethod(methodName, arguments);
            
            // convert "REAL'S HOWTO" to "real's howto"
            Object result =objMethod.invoke(invoker, (Object[])arguments);
            
            System.out.println(result);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}