Monday, 22 April 2013

Printing Docs and Image in android

Now a  day the increasing popularity of android powered devices like Phone, Tablet, Camera  it is also growing need of printing solution  from  this device. Sensing the market need now a day a lot of Printing Application on Google Play.
Printing from android based device is done by  conventional three way Bluetooth, WiFi and USB cable.
Here I am going to discuss how to use Bluetooth to print Images from Android Device.
Create a android Project and named it as BluetoothPrinting, Now  create a java class in your src folder and named it as  "BluetoothShare.java"  inside this Java Class put following code:

import android.net.Uri;
import android.provider.BaseColumns;

public final class BluetoothShare implements BaseColumns {
private BluetoothShare() {

}

/**
 * The permission to access the Bluetooth Share Manager
 */
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_BLUETOOTH_SHARE";

/**
 * The content:// URI for the data table in the provider
 */
public static final Uri CONTENT_URI = Uri.parse("content://com.android.bluetooth.opp/btopp");

/**
 * Broadcast Action: this is sent by the Bluetooth Share component to
 * transfer complete. The request detail could be retrieved by app * as _ID
 * is specified in the intent's data.
 */
public static final String TRANSFER_COMPLETED_ACTION = "android.btopp.intent.action.TRANSFER_COMPLETE";

/**
 * This is sent by the Bluetooth Share component to indicate there is an
 * incoming file need user to confirm.
 */
public static final String INCOMING_FILE_CONFIRMATION_REQUEST_ACTION = "android.btopp.intent.action.INCOMING_FILE_NOTIFICATION";

/**
 * This is sent by the Bluetooth Share component to indicate there is an
 * incoming file request timeout and need update UI.
 */
public static final String USER_CONFIRMATION_TIMEOUT_ACTION = "android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT";

/**
 * The name of the column containing the URI of the file being
 * sent/received.
 * <P>
 * Type: TEXT
 * </P>
 * <P>
 * Owner can Init/Read
 * </P>
 */
public static final String URI = "uri";

/**
 * The name of the column containing the filename that the incoming file
 * request recommends. When possible, the Bluetooth Share manager will
 * attempt to use this filename, or a variation, as the actual name for the
 * file.
 * <P>
 * Type: TEXT
 * </P>
 * <P>
 * Owner can Init/Read
 * </P>
 */
public static final String FILENAME_HINT = "hint";

/**
 * The name of the column containing the filename where the shared file was
 * actually stored.
 * <P>
 * Type: TEXT
 * </P>
 * <P>
 * Owner can Read
 * </P>
 */
public static final String _DATA = "_data";

/**
 * The name of the column containing the MIME type of the shared file.
 * <P>
 * Type: TEXT
 * </P>
 * <P>
 * Owner can Init/Read
 * </P>
 */
public static final String MIMETYPE = "mimetype";

/**
 * The name of the column containing the direction (Inbound/Outbound) of the
 * transfer. See the DIRECTION_* constants for a list of legal values.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Init/Read
 * </P>
 */
public static final String DIRECTION = "direction";

/**
 * The name of the column containing Bluetooth Device Address that the
 * transfer is associated with.
 * <P>
 * Type: TEXT
 * </P>
 * <P>
 * Owner can Init/Read
 * </P>
 */
public static final String DESTINATION = "destination";

/**
 * The name of the column containing the flags that controls whether the
 * transfer is displayed by the UI. See the VISIBILITY_* constants for a
 * list of legal values.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Init/Read/Write
 * </P>
 */
public static final String VISIBILITY = "visibility";

/**
 * The name of the column containing the current user confirmation state of
 * the transfer. Applications can write to this to confirm the transfer. the
 * USER_CONFIRMATION_* constants for a list of legal values.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Init/Read/Write
 * </P>
 */
public static final String USER_CONFIRMATION = "confirm";

/**
 * The name of the column containing the current status of the transfer.
 * Applications can read this to follow the progress of each download. See
 * the STATUS_* constants for a list of legal values.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Read
 * </P>
 */
public static final String STATUS = "status";

/**
 * The name of the column containing the total size of the file being
 * transferred.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Read
 * </P>
 */
public static final String TOTAL_BYTES = "total_bytes";

/**
 * The name of the column containing the size of the part of the file that
 * has been transferred so far.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Read
 * </P>
 */
public static final String CURRENT_BYTES = "current_bytes";

/**
 * The name of the column containing the timestamp when the transfer is
 * initialized.
 * <P>
 * Type: INTEGER
 * </P>
 * <P>
 * Owner can Read
 * </P>
 */
public static final String TIMESTAMP = "timestamp";

/**
 * This transfer is outbound, e.g. share file to other device.
 */
public static final int DIRECTION_OUTBOUND = 0;

/**
 * This transfer is inbound, e.g. receive file from other device.
 */
public static final int DIRECTION_INBOUND = 1;

/**
 * This transfer is waiting for user confirmation.
 */
public static final int USER_CONFIRMATION_PENDING = 0;

/**
 * This transfer is confirmed by user.
 */
public static final int USER_CONFIRMATION_CONFIRMED = 1;

/**
 * This transfer is auto-confirmed per previous user confirmation.
 */
public static final int USER_CONFIRMATION_AUTO_CONFIRMED = 2;

/**
 * This transfer is denied by user.
 */
public static final int USER_CONFIRMATION_DENIED = 3;

/**
 * This transfer is timeout before user action.
 */
public static final int USER_CONFIRMATION_TIMEOUT = 4;

/**
 * This transfer is visible and shows in the notifications while in progress
 * and after completion.
 */
public static final int VISIBILITY_VISIBLE = 0;

/**
 * This transfer doesn't show in the notifications.
 */
public static final int VISIBILITY_HIDDEN = 1;

/**
 * Returns whether the status is informational (i.e. 1xx).
 */
public static boolean isStatusInformational(int status) {
    return (status >= 100 && status < 200);
}

/**
 * Returns whether the transfer is suspended. (i.e. whether the transfer
 * won't complete without some action from outside the transfer manager).
 */
public static boolean isStatusSuspended(int status) {
    return (status == STATUS_PENDING);
}

/**
 * Returns whether the status is a success (i.e. 2xx).
 */
public static boolean isStatusSuccess(int status) {
    return (status >= 200 && status < 300);
}

/**
 * Returns whether the status is an error (i.e. 4xx or 5xx).
 */
public static boolean isStatusError(int status) {
    return (status >= 400 && status < 600);
}

/**
 * Returns whether the status is a client error (i.e. 4xx).
 */
public static boolean isStatusClientError(int status) {
    return (status >= 400 && status < 500);
}

/**
 * Returns whether the status is a server error (i.e. 5xx).
 */
public static boolean isStatusServerError(int status) {
    return (status >= 500 && status < 600);
}

/**
 * Returns whether the transfer has completed (either with success or
 * error).
 */
public static boolean isStatusCompleted(int status) {
    return (status >= 200 && status < 300) || (status >= 400 && status < 600);
}

/**
 * This transfer hasn't stated yet
 */
public static final int STATUS_PENDING = 190;

/**
 * This transfer has started
 */
public static final int STATUS_RUNNING = 192;

/**
 * This transfer has successfully completed. Warning: there might be other
 * status values that indicate success in the future. Use isSucccess() to
 * capture the entire category.
 */
public static final int STATUS_SUCCESS = 200;

/**
 * This request couldn't be parsed. This is also used when processing
 * requests with unknown/unsupported URI schemes.
 */
public static final int STATUS_BAD_REQUEST = 400;

/**
 * This transfer is forbidden by target device.
 */
public static final int STATUS_FORBIDDEN = 403;

/**
 * This transfer can't be performed because the content cannot be handled.
 */
public static final int STATUS_NOT_ACCEPTABLE = 406;

/**
 * This transfer cannot be performed because the length cannot be determined
 * accurately. This is the code for the HTTP error "Length Required", which
 * is typically used when making requests that require a content length but
 * don't have one, and it is also used in the client when a response is
 * received whose length cannot be determined accurately (therefore making
 * it impossible to know when a transfer completes).
 */
public static final int STATUS_LENGTH_REQUIRED = 411;

/**
 * This transfer was interrupted and cannot be resumed. This is the code for
 * the OBEX error "Precondition Failed", and it is also used in situations
 * where the client doesn't have an ETag at all.
 */
public static final int STATUS_PRECONDITION_FAILED = 412;

/**
 * This transfer was canceled
 */
public static final int STATUS_CANCELED = 490;

/**
 * This transfer has completed with an error. Warning: there will be other
 * status values that indicate errors in the future. Use isStatusError() to
 * capture the entire category.
 */
public static final int STATUS_UNKNOWN_ERROR = 491;

/**
 * This transfer couldn't be completed because of a storage issue.
 * Typically, that's because the file system is missing or full.
 */
public static final int STATUS_FILE_ERROR = 492;

/**
 * This transfer couldn't be completed because of no sdcard.
 */
public static final int STATUS_ERROR_NO_SDCARD = 493;

/**
 * This transfer couldn't be completed because of sdcard full.
 */
public static final int STATUS_ERROR_SDCARD_FULL = 494;

/**
 * This transfer couldn't be completed because of an unspecified un-handled
 * OBEX code.
 */
public static final int STATUS_UNHANDLED_OBEX_CODE = 495;

/**
 * This transfer couldn't be completed because of an error receiving or
 * processing data at the OBEX level.
 */
public static final int STATUS_OBEX_DATA_ERROR = 496;

/**
 * This transfer couldn't be completed because of an error when establishing
 * connection.
 */
public static final int STATUS_CONNECTION_ERROR = 497;
The above code is  creating  a  Util class to give access of printer through bluetooth. It is using "android.provider.BaseColumns" to support the inbuilt feature of Android device to support Bluetooth printing.
Now put this code in your MainActivity.java class . This Main Activity class is using your Util class("BluetoothShare.java") to send the data(here I am sending image file) for printing on a specific device.

public class MainActivity extends Activity {

private static final String TAG = "BTSendFile";

private final int ACTIVITY_SELECT_IMAGE = 1;
private final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
private Button select;
private Button sendDirectly;
private TextView textStatus;
private Uri uri;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textStatus = (TextView) findViewById(R.id.sendStatus);
    select = (Button) findViewById(R.id.select);
    sendDirectly = (Button) findViewById(R.id.sendDirectly);

    select.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
        }
    });

    sendDirectly.setEnabled(false);
    sendDirectly.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (btAdapter.isEnabled()) {
                Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                final String btDeviceName = "PIXMA mini260";// here yo can put your device name 
                BluetoothDevice device = null;

                for (BluetoothDevice itDevice : devices) {
                    if (btDeviceName.equals(itDevice.getName())) {
                        device = itDevice;
                    }
                }
                if (device != null) {

                    ContentValues values = new ContentValues();
                    // values.put(BluetoothShare.URI, Uri.fromFile(new
                    // File(uri.getPath())).toString());
                    values.put(BluetoothShare.URI, uri.toString());
                    values.put(BluetoothShare.MIMETYPE, "image/jpeg");
                    values.put(BluetoothShare.DESTINATION, device.getAddress());
                    values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
                    Long ts = System.currentTimeMillis();
                    values.put(BluetoothShare.TIMESTAMP, ts);
                    final Uri contentUri = getApplicationContext().getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
                    Log.v(TAG, "Insert contentUri: " + contentUri + "  to device: " + device.getName());
                } else {
                    textStatus.setText("Bluetooth remote device not found");
                }
            } else {
                textStatus.setText("Bluetooth not activated");
            }
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case ACTIVITY_SELECT_IMAGE:
        if (resultCode == RESULT_OK) {
            uri = data.getData();
            String filePath = uri.getPath();
            textStatus.setText(filePath);
            sendDirectly.setEnabled(true);
        } else {
            sendDirectly.setEnabled(false);
        }
        break;
    default:
        assert false;
    }
}
This is main_activity.xml file. Put following code
<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:id="@+id/sendStatus"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="8dp"
    android:text="Please select file" >
</TextView>

<Button
    android:id="@+id/select"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Select file" >
</Button>

<Button
    android:id="@+id/sendDirectly"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send file" >
</Button>
</LinearLayout>
By using above code you can print your data through bluetooth in android. 
Note:- Printing in android is depends upon hardware support so some time this code  will not  work  in some device. 
Thanks Happy Coding!!!

Monday, 1 April 2013

Memory Management in Android


Android’s process and memory management is a little unusual. Like Java and .NET, Android uses its own run time and virtual machine to manage application memory.
Unlike either of these frameworks, the Android run time also manages the process lifetimes.
Android ensures application responsiveness by stopping and killing processes as necessary to free resources for higher-priority applications.

Each Android application runs in a separate process within its own Dalvik instance,
relinquishing all responsibility for memory and process management to the Android run time, which stops and kills processes as necessary to manage resources.

Dalvik and the Android run time sit on top of a Linux kernel that handles low-level hardware interaction including drivers and memory management,while a set of APIs provides access to all of the under- lying services, features, and hardware.
Dalvik Virtual Machine  is a register-based virtual machine that’s been optimized to ensure that a device can run multiple instances efficiently. It relies on the Linux kernel for threading and low-level memory management.

The Dalvik Virtual Machine
One of the key elements of Android is the Dalvik virtual machine. Rather than use a traditional Java virtual machine (VM) such as Java ME (Java Mobile Edition),
Android uses its own custom VM designed to ensure that multiple instances run efficiently on a single device.
The Dalvik VM uses the device’s underlying Linux kernel to handle low-level functionality including security, threading, and process and memory management.
All Android hardware and system service access is managed using Dalvik as a middle tier. By using a VM to host application execution,
developers have an abstraction layer that ensures they never have to worry about a particular hardware implementation.
The Dalvik VM executes Dalvik executable files, a format optimized to ensure minimal memory foot- print. The .dex executables are created by transforming Java language compiled classes using the tools supplied within the SDK.

Understanding Application Priority and Process States
The order in which processes are killed to reclaim resources is determined by the priority of the hosted applications. An application’s priority is equal to its highest-priority component.

Where two applications have the same priority, the process that has been at a lower priority longest will be killed first. Process priority is also affected by inter process dependencies; if an application has a dependency on a Service or Content Provider supplied by a second application, the secondary application will have at least as high a priority as the application it supports.

All Android applications will remain running and in memory until the system needs its resources for other applications.

It’s important to structure your application correctly to ensure that its priority is appropriate for the work it’s doing. If you don’t, your application could be killed while it’s in the middle of something important.

The following list details each of the application states shown in Figure (see the attached image) explaining how the state is determined by the application components comprising it:


Active Processes Active (foreground) processes are those hosting applications with components currently interacting with the user. These are the processes Android is trying to keep responsive by reclaiming resources. There are generally very few of these processes, and they will be killed only as a last resort.

Active processes include:
* Activities in an “active” state; that is, they are in the foreground and responding to user events. You will explore Activity states in greater detail later in this chapter.
* Activities, Services, or Broadcast Receivers that are currently executing an onReceive event handler.
* Services that are executing an onStart, onCreate, or onDestroy event handler.

Visible Processes Visible, but inactive processes are those hosting “visible” Activities. As the name suggests, visible Activities are visible, but they aren't in the foreground or responding to user events. This happens when an Activity is only partially obscured (by a non-full-screen or transparent Activity). There are generally very few visible processes, and they’ll only be killed in extreme circumstances to allow active processes to continue.

Started Service Processes Processes hosting Services that have been started. Services support ongoing processing that should continue without a visible interface. Because Services don’t interact directly with the user, they receive a slightly lower priority than visible Activities. They are still considered to be foreground processes and won’t be killed unless resources are needed for active or visible processes.

Background Processes Processes hosting Activities that aren’t visible and that don’t have any Services that have been started are considered background processes. There will generally be a large number of background processes that Android will kill using a last-seen-first-killed pat- tern to obtain resources for foreground processes.

Empty Processes To improve overall system performance, Android often retains applications in memory after they have reached the end of their lifetimes. Android maintains this cache to improve the start-up time of applications when they’re re-launched. These processes are rou- tinely killed as required.

How to use memory efficiently
Android manages opened applications which are running in the background, so officially you shouldn’t care about that. This means that it closes the applications when the system needs more memory. However, most android users are not very satisfied with how it does its things because sometimes it leaves too many processes running which causes sluggishness’ in everyday performance. We can use advanced task killer/task manager and it does its job very well.




Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...