Tuesday, 24 December 2013

Android default downloader to downaload files code sample

Permissions Required :

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

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



activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:layout_gravity="center"

    android:gravity="center"

    android:orientation="vertical" >



    <Button

        android:id="@+id/button1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Download" />



    <Button

        android:id="@+id/button2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="show Download" />



</LinearLayout>



MainActivity.class :

package com.example.samppledefaultdownloader;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
 private long enqueue;
 private DownloadManager dm;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Button b = (Button) findViewById(R.id.button1);
  Button b1 = (Button) findViewById(R.id.button2);
  b.setOnClickListener(this);
  b1.setOnClickListener(this);
  dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

  BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
     long downloadId = intent.getLongExtra(
       DownloadManager.EXTRA_DOWNLOAD_ID, 0);
     Query query = new Query();
     query.setFilterById(enqueue);
     Cursor c = dm.query(query);
     if (c.moveToFirst()) {
      int columnIndex = c
        .getColumnIndex(DownloadManager.COLUMN_STATUS);
      if (DownloadManager.STATUS_SUCCESSFUL == c
        .getInt(columnIndex)) {
       String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
       Log.i("123456", "Download successfull +" + Uri.parse(uriString).getPath());
      }
     }
    }
   }
  };

  registerReceiver(receiver, new IntentFilter(
    DownloadManager.ACTION_DOWNLOAD_COMPLETE));
 }

 @Override
 public void onClick(View v) {
  if (v.getId() == R.id.button1) {
   Request request = new Request(Uri.parse("http://upload.wikimedia.org/wikipedia/commons/b/b8/Charminar_sumeet_photography_3.JPG"));
   request.setDestinationInExternalPublicDir("/meher-samples/Download-example/", "charminar.png"); // enable this line to download in custom path.
   request.setTitle("charminar");
   enqueue = dm.enqueue(request);
  }
  else if (v.getId() == R.id.button2) {
   Intent i = new Intent();
   i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
   startActivity(i);
  }
 }
}

Monday, 23 December 2013

Android Extracting apk from the device sample code


The following code explains you how to extract apk which is installed in the device.


Permissions Required :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


activity_main.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent" >



    <ListView

        android:id="@+id/list"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />



</RelativeLayout>



MainActivity.class :


package com.example.simpleapkextractor;



import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.nio.channels.FileChannel;

import java.util.ArrayList;

import java.util.Iterator;



import android.app.Activity;

import android.app.ProgressDialog;

import android.content.pm.ApplicationInfo;

import android.content.pm.PackageManager;

import android.graphics.drawable.Drawable;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Environment;

import android.util.Log;

import android.view.View;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.Toast;



public class MainActivity extends Activity implements OnItemClickListener {

PackageManager manager;

private ArrayAdapter<String> mAdapter = null;

ArrayList<String> mPkgs = new ArrayList<String>();

ListView mListView;



@Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  mListView = (ListView) findViewById(R.id.list);

  mListView.setOnItemClickListener(this);

  new LoadMainContent().execute();

 }



 class LoadMainContent extends AsyncTask<Void, Void, Void> {

  private static final String TAG = "123456";

  ProgressDialog mProgressDialog = null;



  protected Void doInBackground(Void[] paramArrayOfVoid) {

   MainActivity.this.manager = getPackageManager();

   Iterator<?> localIterator = manager.getInstalledApplications(128).iterator();

   try {

    while (localIterator.hasNext()) {

     ApplicationInfo localApplicationInfo = (ApplicationInfo) localIterator.next();

     String pkgName = localApplicationInfo.packageName;

     String appLabel = manager.getApplicationLabel(localApplicationInfo).toString();

     Drawable icon = manager.getApplicationIcon(localApplicationInfo.packageName);

     Log.i(TAG, "pkg: " + pkgName);

     mPkgs.add(pkgName);

    }

   } catch (Exception localException) {

    localException.printStackTrace();

   }

   return null;

  }

  protected void onPostExecute(Void paramVoid) {

   super.onPostExecute(paramVoid);

   this.mProgressDialog.dismiss();

   mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, mPkgs);

   mListView.setAdapter(mAdapter);

  }

  protected void onPreExecute() {

   super.onPreExecute();

   this.mProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Loading Apps");

  }

 }

 @Override

 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

  letsExtract(arg2);

 }



 private void letsExtract(int paramInt) {

  String str = (mPkgs.get(paramInt));

  ApplicationInfo localApplicationInfo = getAppInfo(str);

  File localFile1;

  File localFile2;

  if (localApplicationInfo.packageName.equalsIgnoreCase(str)) {

   localFile1 = new File(localApplicationInfo.publicSourceDir);

   localFile2 = new File(Environment.getExternalStorageDirectory() + "/Meher-ExtractAPKs/" + str + ".apk");

   File localFile3 = new File(Environment.getExternalStorageDirectory() + "/Meher-samples/ExtractAPK/");

   if (!localFile3.exists()) {

    localFile3.mkdirs();

   }

   try {

    FileChannel localFileChannel1 = new FileInputStream(localFile1).getChannel();

    FileChannel localFileChannel2 = new FileOutputStream(localFile2).getChannel();

    localFileChannel2.transferFrom(localFileChannel1, 0L, localFileChannel1.size());

    localFileChannel1.close();

    localFileChannel2.close();

    Toast.makeText(this, "" + mPkgs.get(paramInt), 1).show();

    Log.d("123456", "success");

   } catch (Exception e) {

    e.printStackTrace();

   }
  }
 }

 ApplicationInfo getAppInfo(String paramString) {

  Iterator<?> localIterator = this.manager.getInstalledApplications(128).iterator();

  ApplicationInfo localApplicationInfo = null;

  while (localIterator.hasNext()) {

   localApplicationInfo = (ApplicationInfo) localIterator.next();

   if (localApplicationInfo.packageName.equalsIgnoreCase(paramString)) {

    return localApplicationInfo;

   }
  }

  return localApplicationInfo;

 }
}

Note : you can extend this app by using custom adapter to show proper app name with app icon.

Friday, 20 December 2013

Android Eclipse setup procedure

To setup android in your pc you should have following system requirements :

Operating Systems
  • Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
  • Mac OS X 10.5.8 or later (x86 only)
  • Linux (tested on Ubuntu Linux, Lucid Lynx)
    • GNU C Library (glibc) 2.7 or later is required.
    • On Ubuntu Linux, version 8.04 or later is required.
    • 64-bit distributions must be capable of running 32-bit applications
Required Softwares 
Java should be installed in your PC.You can download  JDK 6 here.

You can download android setup from android developers site.Once you download you are ready to code.
It consists of following
  • Eclipse + ADT plugin
  • Android SDK Tools
  • Android Platform-tools
  • The latest Android platform
  • The latest Android system image for the emulator.
After downloading,Extract the zip and run the eclipse and set the sdk path in the eclipse.
Now you are ready to create an sample android application.
Happy coding.