Tuesday, December 20, 2011

Root the Amazon Kindle Fire


Things You Need

  • A PC running Windows Vista or Windows 7
  • The Android SDK which has to be installed in your PC (click here for install details)
  • SuperOneClick v 2.2 (get it here) — This is the software you will use to root the device.
  • USB cable for connecting your tablet to your PC
  • Amazon Kindle Fire

Step-by-step Procedure

Step 1: Install the Android SDK into your PC. The details about how to install the software development kit will not be discussed here because it’s a totally different subject on its own.
Step 2: You now have to turn on “Allow Installation of Applications From Unknown Sources”. This can be done by tapping the Settings icon at the top right corner. Then, go to More->Device. You can turn on the setting from there.


Step 3: Connect the Kindle Fire to your PC using the micro USB to USB cable. If the connect screen comes up on the screen of the Kindle Fire, please do not tap on connect for this will enable USB connection.

Step 4: Modify android_winusb.inf
  1. Go to the folder where the SDK is installed.
  2. Open Extras->Google->USB Driver.
  3. Right click on android_winusb.inf and choose “Open with” then select Notepad.
  4. Look for [Google.NTx86] and [Google.NTamd64] in the text that you just opened.
  5. Copy and paste the code below right beneath [Google.NTx86] and [Google.NTamd64] line (make sure to save the file after editing):
;Kindle Fire
%SingleAdbInterface% = USB_Install, USB\VID_1949&PID_0006
%CompositeAdbInterface% = USB_Install, USB\VID_1949&PID_0006&MI_01
Step 5: Create adb_usb.ini and save it into the .android folder.
  1. Open Notepad.
  2. Type 0x1949 and then save the file as adb_usb.ini
  3. Open Computer.
  4. Go to Users.
  5. Open the user login name folder you are using.
  6. Copy and paste adb_usb.ini into the .android folder which you will see under the login name folder.
Step 6: Update the USB driver for the Kindle Fire.
  1. Open Device Manager from the Control Panel window.
  2. Look for Kindle under Other Devices.
  3. Right click Kindle and select “Update Driver Software”.
  4. Select “Browse my computer for driver software”.
  5. We now have to browse for the USB driver file we edited earlier, which should be located under Android SDK folder->Extras->Google.
  6. After choosing the directory, just click Next and a prompt saying “Windows can’t verify the publisher of this driver software” will show up. Click “Install this driver software anyway”.
Step 7: Check if Android SDK will now recognize the Kindle Fire.
  1. Open up a command prompt window.
  2. Go to the folder were the Android SDK is installed using the cd command.
  3. From the Android SDK folder, access the platform-tools folder by still using the cd command.
  4. Under the platform-tools folder, issue the adb kill-server command.
  5. Next you have to issue the adb devices command. This will give you text similar to the one below. This will indicate that the SDK recognizes the Kindle Fire.
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
5246002600000001    device

Step 8: The last part of the process is to root the device. Since we already downloaded the software from Shortfuse, we just have to extract it. After extracting the software, you just have to run it and it will automatically do its charm.

Now that rooting is done, your Kindle Fire will now be open for endless possibilities. More third-party apps can now be installed on the device


Thursday, December 8, 2011

Check Screen timeout / KeyGuard Lock

Check for the Screen timeout or not!


PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);


if(pm.isScreenOn())
{
      Toast.makeText(this,"Screen is not locked", 20).show();
}else
     Toast.makeText(this,"Screen is time out", 20).show();



Wednesday, December 7, 2011

Activity Launch Modes


Activity Launch Modes - A simple explanation in a table.

An Android Activity launch mode dictates to which Task an Activity is created and how it is instantiated. Its a tiny bit confusing to figure out exactly what launch mode you need from the official documentation so I've created a small table to help.

First of all here is a brief definition of some of the terms:

  • Task - A "stack of Activities" in your application. If an Activity is sent to the background (by pressing the HOME key whilst viewing it, for example) then the whole Task (and all the Activities inside it) will be sent back as well. If the user then clicks on your application, the task (and the order of its activities) come forward.



  • Root of a task - The first Activity in a Task. There is always one of these in a Task.




  • Shared Preferences Example (Run application from last Activity after Home Press)


    Shared Preferences

    Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity (which is not discussed here). 

    The context object lets you retrieve SharedPreferences through the methodContext.getSharedPreferences(). 

    In my example, I will set 2 preferences i.e. MyName and MyWallpaper in one activity i.eManageSharedPref.java. Retrieve these values in the next activity – ViewSharedPrefs.java. The second activity displays my preferred name in a list view and also resets the android wallpaper to the image that I had set as a preferred wallpaper in the first activity. When you run this application, if you come back to the home, you will see the wall paper is reset. 

    Here is the code in ManageSharesPrefs:

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_READABLE);
            SharedPreferences.Editor prefsEditor = myPrefs.edit();
            prefsEditor.putString(MY_NAME"Sai");
            prefsEditor.putString(MY_WALLPAPER"f664.PNG");
            prefsEditor.commit();
            
    First, I obtain a SharedPreferences object making it readable by all. The first parameter is a name of a file that stores my preferences. This automatically creates the xml file if it does not exist and then stores in the same. 

    Next, I edit it. That creates an editor object, using which I input my preferences. Here, for the wall paper, I have put an image name. I also need to push the actual image file into the android storage which I do this way.

    adb push <local> <remote>

    In this case it is 

    adb push f664.PNG /data/misc/wallpaper/f664.PNG

    This command creates a folder called wallpaper in /data/misc and copies the f664.PNG file from my current location to the android storage.

    When I click the “View Shared Preferences” button, I am taken to the next activity. Here is the code in ViewSharedPrefs that gets executed:

            SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_READABLE);
            String prefName = myPrefs.getString(MY_NAME"nothing");
            String wallPaper = myPrefs.getString(MY_WALLPAPERnull);
            
            if(wallPaper != null) {
                try {
                      Bitmap bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper);
                      Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper);
                      setWallpaper(bm);
                      Toast.makeText(this"Wall paper has been changed." +
                                  "You may go to the home screen to view the same", Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException fe){
                      Log.e(getClass().getSimpleName(),"File not found");
                } catch (IOException ie) {
                      Log.e(getClass().getSimpleName()," IO Exception");
                }
                
            }
            ArrayList<String> results = new ArrayList<String>();
            results.add("Your Preferred name is: " + prefName);
          this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

    There are 3 steps to understand here:

    1.    Step 1: Retrieve the shared prefs data from the object.

            SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_READABLE);
            String prefName = myPrefs.getString(MY_NAME"nothing");
            String wallPaper = myPrefs.getString(MY_WALLPAPERnull);

    2.    Step 2: Display the name
            ArrayList<String> results = new ArrayList<String>();
            results.add("Your Preferred name is: " + prefName);
          this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

    3.    Step 3: Reset the wall paper.
            if(wallPaper != null) {
                try {
                      Bitmap bm = BitmapFactory.decodeFile("/data/misc/wallpaper/"+wallPaper);
                      Log.d(getClass().getSimpleName(),"Wallpaper name is: "+ wallPaper);
                      setWallpaper(bm);
                      Toast.makeText(this"Wall paper has been changed." +
                                  "You may go to the home screen to view the same", Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException fe){
                      Log.e(getClass().getSimpleName(),"File not found");
                } catch (IOException ie) {
                      Log.e(getClass().getSimpleName()," IO Exception");
                }
                
            }
    It is this simple. The complete code is available here.

    By help of Shered Prefrences we can solve the Problem of 

    Show last viewed Activity When press Home 



    Saturday, November 19, 2011

    Android Add Permission Dynemically

    public abstract boolean addPermission (PermissionInfo info)
    Since: API Level 1
    Add a new dynamic permission to the system. For this to work, your package must have defined a permission tree through the <permission-tree> tag in its manifest. A package can only add permissions to trees that were defined by either its own package or another with the same user id; a permission is in a tree if it matches the name of the permission tree + ".": for example, "com.foo.bar" is a member of the permission tree "com.foo".
    It is good to make your permission tree name descriptive, because you are taking possession of that entire set of permission names. Thus, it must be under a domain you control, with a suffix that will not match any normal permissions that may be declared in any applications that are part of that domain.
    New permissions must be added before any .apks are installed that use those permissions. Permissions you add through this method are remembered across reboots of the device. If the given permission already exists, the info you supply here will be used to update it.
    Parameters
    infoDescription of the permission to be added.
    Returns
    • Returns true if a new permission was created, false if an existing one was updated.
    Throws
    SecurityExceptionif you are not allowed to add the given permission name.


    Thursday, November 17, 2011

    Android Facebook API example using FBRocket


    Android Facebook API example using FBRocket

    This post is posted as per the request of many comments on Android JTwitter Example.
    Now let proceed ahead with Facebook using FBrocket.
    Using FB rocket we can update our facebook profile status from mobile application.
    Before we get into coding we got to make sure that we do the following steps
    1. Import the FBrocket JAR file to the eclipse project and add it to JAR libraries. Download here ( http://www.xeomax.net/fbrocket/download.php?d=bin&v=0.1a )
    2. Make sure you have created an application inhttp://www.facebook.com/developers/#!/developers/createapp.php
    3. Note down application name and API key, do not reveal API key to anybody.
    [sourcecode language="java"]
    package org.androidpeople.facebook;
    import net.xeomax.FBRocket.FBRocket;
    import net.xeomax.FBRocket.Facebook;
    import net.xeomax.FBRocket.LoginListener;
    import net.xeomax.FBRocket.ServerErrorException;
    import android.app.Activity;
    import android.os.Bundle;
    public class FacebookRocketExample extends Activity implements LoginListener {
    private FBRocket fbRocket;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    shareFacebook();
    }
    public void shareFacebook() {
    fbRocket = new FBRocket(this, "Your App Name",
    "Your API Key");
    if (fbRocket.existsSavedFacebook()) {
    fbRocket.loadFacebook();
    } else {
    fbRocket.login(R.layout.main);
    }
    }
    @Override
    public void onLoginFail() {
    fbRocket.displayToast("Login failed!");
    fbRocket.login(R.layout.main);
    }
    @Override
    public void onLoginSuccess(Facebook facebook) {
    // TODO Auto-generated method stub
    fbRocket.displayToast("Login success!");
    try {
    facebook.setStatus("This is your status");
    fbRocket.displayDialog("Status Posted Successfully!! "
    facebook.getStatus());
    } catch (ServerErrorException e) {
    if (e.notLoggedIn()) {
    fbRocket.login(R.layout.main);
    } else {
    System.out.println(e);
    }
    }
    }
    }
    [/sourcecode]
    Screenshots :
    Download : This Example Click Here


    Tuesday, November 15, 2011

    Delete file in Internal Storage


    Delete file in Internal Storage

    Here method deleteFile() delete the given  file associated with this Context's application package.

    Delete file in Internal Storage
    Delete file in Internal Storage

    package com.exercise.AndroidInternalStorage;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.DialogInterface.OnClickListener;
    import android.os.Bundle;
    import android.view.View;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class AndroidInternalStorageActivity extends Activity {
     
     EditText edFileName, edContent;
     Button btnSave;
     ListView listSavedFiles;
     
     String[] SavedFiles;
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            edFileName = (EditText)findViewById(R.id.filename);
            edContent = (EditText)findViewById(R.id.content);
         btnSave = (Button)findViewById(R.id.save);
         listSavedFiles = (ListView)findViewById(R.id.list);
         
         ShowSavedFiles();
         
         btnSave.setOnClickListener(new Button.OnClickListener(){
    
       @Override
       public void onClick(View arg0) {
        // TODO Auto-generated method stub
        String fileName = edFileName.getText().toString();
        String content = edContent.getText().toString();
        
        FileOutputStream fos;
        try {
         fos = openFileOutput(fileName, Context.MODE_PRIVATE);
         fos.write(content.getBytes());
         fos.close();
         
         Toast.makeText(
           AndroidInternalStorageActivity.this, 
           fileName + " saved", 
           Toast.LENGTH_LONG).show();
         
        } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
        
        ShowSavedFiles();
        
       }});
         
         listSavedFiles.setOnItemClickListener(listSavedFilesOnItemClickListener);
         
        }
        
        void ShowSavedFiles(){
         SavedFiles = getApplicationContext().fileList();
         ArrayAdapter<String> adapter
         = new ArrayAdapter<String>(this,
           android.R.layout.simple_list_item_1,
           SavedFiles);
      
         listSavedFiles.setAdapter(adapter);
        }
        
        OnItemClickListener listSavedFilesOnItemClickListener
        = new OnItemClickListener(){
    
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
       // TODO Auto-generated method stub
       String clickedFile = (String) parent.getItemAtPosition(position);
       OpenFileDialog(clickedFile);
      }
         
        };
        
        void OpenFileDialog(final String file){
         
         //Read file in Internal Storage
         FileInputStream fis;
         String content = "";
         try {
          fis = openFileInput(file);
          byte[] input = new byte[fis.available()];
          while (fis.read(input) != -1) {}
          content += new String(input);
         } catch (FileNotFoundException e) {
          e.printStackTrace();
         } catch (IOException e) {
          e.printStackTrace(); 
         }
         
         //Create a custom Dialog
         AlertDialog.Builder fileDialog 
         = new AlertDialog.Builder(AndroidInternalStorageActivity.this);
         fileDialog.setTitle(file);
         
         TextView textContent = new TextView(AndroidInternalStorageActivity.this);
         textContent.setText(content);
            LayoutParams textViewLayoutParams 
             = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            textContent.setLayoutParams(textViewLayoutParams);
            
            fileDialog.setView(textContent);
            
            fileDialog.setPositiveButton("OK", null);
            
            //Delete file in Internal Storage
            OnClickListener DeleteListener = new OnClickListener(){
    
       @Override
       public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        deleteFile(file);
        Toast.makeText(
          AndroidInternalStorageActivity.this, 
          file + " deleted", 
          Toast.LENGTH_LONG).show();
        ShowSavedFiles();
       }
     
            };
      fileDialog.setNeutralButton("DELETE", DeleteListener);
            
            fileDialog.show();
        }
    }


    Download the files.