Category Archives: Android

Android Lollipop 5.0 APIs – special feature

android-lollipop-new-features

Some of the features of Lollipop 5.0 :

  1. Material design

  2. Concurrent documents and activities in the recents screen

  3. WebView updates

  4. Screen capturing and sharing

  5. Notifications

  6. Graphics

  7. Camera API for advanced camera capabilities

  8. Bluetooth Low Energy

  9. Scheduling jobs

  10. Developer tools for battery usage

  1. Material design :

Android 5.0 adds support for Android””s new material design style. You can create apps with material design that are visually dynamic and have UI element transitions that feel natural to users. This support includes:

  • The material theme
  • View shadows
  • The RecyclerView widget
  • Drawable animation and styling effects
  • Material design animation and activity transition effects
  • Animators for view properties based on the state of the view
  • Customizable UI widgets and app bars with color palettes that you control

Animated and non-animated drawables based on XML vector graphics

  1. Concurrent documents and activities in the recents screen :

In previous releases, the recents screen could only display only one task for each app that the user interacted with most recently. Now your app can open more tasks as needed for additional concurrent activities for documents. This feature facilitates multitasking by letting users quickly switch between individual activities and documents from the recents screen, with a consistent switching experience across all apps. Examples of such concurrent tasks might include open tabs in a web browser app, documents in a productivity app, concurrent matches in a game, or chats in a messaging app. Your app can manage its tasks through the ActivityManager.AppTask class.

3.WebView updates

Android 5.0 updates the WebView implementation to Chromium M37, bringing security and stability enhancements, as well as bug fixes. The default user-agent string for a WebView running on Android 5.0 has been updated to incorporate 37.0.0.0 as the version number.

This release introduces the PermissionRequest class, which allows your app to grant the WebView permission to access protected resources like the camera and microphone, through web APIs such as getUserMedia(). Your app must have the appropriate Android permissions for these resources in order to grant the permissions to the WebView.

  1. Screen capturing and sharing

Android 5.0 lets you add screen capturing and screen sharing capabilities to your app with the new android.media.projection APIs. This functionality is useful, for example, if you want to enable screen sharing in a video conferencing app.
The new createVirtualDisplay() method allows your app to capture the contents of the main screen (the default display) into a Surface object, which your app can then send across the network. The API only allows capturing non-secure screen content, and not system audio. To begin screen capturing, your app must first request the user’s permission by launching a screen capture dialog using an Intent obtained through the createScreenCaptureIntent() method.

  1. Notifications

Lock screen notifications

Lock screens in Android 5.0 have the ability to present notifications. Users can choose via Settings whether to allow sensitive notification content to be shown over a secure lock screen.

Your app can control the level of detail visible when its notifications are displayed over the secure lock screen. To control the visibility level, call setVisibility() and specify one of these values:

  • VISIBILITY_PRIVATE: Shows basic information, such as the notification’s icon, but hides the notification’s full content.
  • VISIBILITY_PUBLIC: Shows the notification’s full content.
  • VISIBILITY_SECRET: Shows nothing, excluding even the notification’s icon.

When the visibility level is VISIBILITY_PRIVATE, you can also provide a redacted version of the notification content that hides personal details. For example, an SMS app might display a notification that shows “You have 3 new text messages” but hides the message content and senders. To provide this alternative notification, first create the replacement notification using Notification.Builder. When you create the private notification object, attach the replacement notification to it through the setPublicVersion() method.

Notifications metadata

Android 5.0 uses metadata associated with your app notifications to sort the notifications more intelligently. To set the metadata, call the following methods in Notification.Builder when you construct the notification:

  • setCategory(): Tells the system how to handle your app notifications when the device is in priority mode (for example, if a notification represents an incoming call, instant message, or alarm).
  • setPriority(): Marks the notification as more or less important than normal notifications. Notifications with the priority field set to PRIORITY_MAX or PRIORITY_HIGH appear in a small floating window if the notification also has sound or vibration.
  • addPerson(): Enables you to add one or more people who are relevant to a notification. Your app can use this to signal to the system that it should group together notifications from the specified people, or rank notifications from these people as being more important.
  1. Graphics

Support for OpenGL ES 3.1

Android 5.0 adds Java interfaces and native support for OpenGL ES 3.1. Key new functionality provided in OpenGL ES 3.1 includes:

  • Compute shaders
  • Separate shader objects
  • Indirect draw commands
  • Multisample and stencil textures
  • Shading language improvements
  • Extensions for advanced blend modes and debugging
  • Backward compatibility with OpenGL ES 2.0 and 3.0

The Java interface for OpenGL ES 3.1 on Android is provided with GLES31. When using OpenGL ES 3.1, be sure that you declare it in your manifest file with the <uses-feature> tag and the android:glEsVersion attribute. For example:

<manifest><uses-feature android:glEsVersion=”0x00030001″ />

</manifest>

  1. Camera API for advanced camera capabilities

Android 5.0 introduces the new android.hardware.camera2 API to facilitate fine-grain photo capture and image processing. You can now programmatically access the camera devices available to the system with getCameraIdList() and connect to a specific device with openCamera(). To start capturing images, create a CameraCaptureSession and specify the Surface objects to send captured images. The CameraCaptureSession can be configured to take single shots or multiple images in a burst.

  1. Bluetooth Low Energy :

Android 4.3 introduced platform support for Bluetooth Low Energy (Bluetooth LE) in the central role. In Android 5.0, an Android device can now act as a Bluetooth LE peripheral device. Apps can use this capability to make their presence known to nearby devices. For instance, you can build apps that allow a device to function as a pedometer or health monitor and communicate its data with another Bluetooth LE device.

The new android.bluetooth.le APIs enable your apps to broadcast advertisements, scan for responses, and form connections with nearby Bluetooth LE devices. To use the new advertising and scanning features, add the BLUETOOTH_ADMIN permission in your manifest. When users update or download your app from the Play Store, they are asked to grant the following permission to your app: “Bluetooth connection information: Allows the app to control Bluetooth, including broadcasting to or getting information about nearby Bluetooth devices.”

  1. Scheduling jobs :

In addition to new features, Android 5.0 emphasizes improvements in battery life. Use the new APIs and tool to understand and optimize your app’s power consumption.

Android 5.0 provides a new JobScheduler API that lets you optimize battery life by defining jobs for the system to run asynchronously at a later time or under specified conditions (such as when the device is charging). Job scheduling is useful in such situations as:

  • The app has non-user-facing work that you can defer.
  • The app has work you””d prefer to do when the unit is plugged in.
  • The app has a task that requires network access or a Wi-Fi connection.
  • The app has a number of tasks that you want to run as a batch on a regular schedule.

Use the JobInfo.Builder class to configure how the scheduled task should run. You can schedule the task to run under specific conditions, such as:

  • Start when the device is charging
  • Start when the device is connected to an unmetered network
  • Start when the device is idle
  • Finish before a certain deadline or with a minimum delay

For example, you can add code like this to run your task on an unmetered network:

JobInfo uploadTask = new JobInfo.Builder(mJobId,  mServiceComponent /* JobService component */).setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED)
.build();

JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(uploadTask);

If the device has stable power (that is, it has been plugged in for more than 2 minutes and the battery is at a healthy level), the system will run any scheduled job that is ready to run, even if the job’s deadline has not expired.

  1. Developer tools for battery usage :

The new dumpsys batterystats command generates interesting statistical data about battery usage on a device, organized by unique user ID (UID). The statistics include:

 

  • History of battery related events
  • Global statistics for the device
  • Approximate power use per UID and system component
  • Per-app mobile ms per packet
  • System UID aggregated statistics
  • App UID aggregated statistics

 

Use the –help option to learn about the various options for tailoring the output. For example, to print battery usage statistics for a given app package since the device was last charged, run this command:

 

$ adb shell dumpsys batterystats –charged <package-name>

 

How to carry an Object through an Intent to the Next Activity in Android Using “Parcelable” interface

How to carry an Object through an Intent to the Next Activity in Android Using “Parcelable” interface

Download the Sample Demo of this app here ParcelableDemo.

We all know that we carry data from one activity to another activity using Intents in Android. We put the data into the intent as extra data in the form of key value pair. And the targeted activity will call its method “getIntent()” to get the intent because of which that activity started and then we can get the data in the form of a Bundle object by call getExtras() method on that intent.

 

However we can not directly carry an object through an Intent by putting it as extra data.

 

An Intent can contain objects of only those classes which are implementing “Parcelable” interface or “Serializable” interface.

Here we will be talking about the “Parcelable” interface.

 

In this example we have created a class UserInfo,which will be holding the information about the user i.e. UserName and UserID.

 

We would like to put an Object of UserInfo as extra data and receive into another activity which will be activated by the Intent.
To be able to put UserInfo object into the Intent object, the UserInfo class must implement Parcelable interface.

UserInfo.java

package in.bitcode.parcelabledemo;import android.os.Parcel;
import android.os.Parcelable;

public class UserInfo implements Parcelable {

private String userName;
private int userID;

public static final Parcelable.Creator<UserInfo> CREATOR = new UserInfoCreatorFromParcel();

public UserInfo(String userName, int userID) {
this.userName = userName;
this.userID = userID;
}

public int getUserID() {
return userID;
}

public String getUserName() {
return userName;
}

@Override
public int describeContents() {
return 0;
}

@Overrid
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(userName);
dest.writeInt(userID);
}

private static class UserInfoCreatorFromParcel implements Parcelable.Creator<UserInfo> {

@Override
public UserInfo createFromParcel(Parcel source) {
return new UserInfo( source.readString(), source.readInt() );
}

@Override
public UserInfo[] newArray(int size) {
return null;
}

}

}

 

When an Object of UserInfo is added to intent by using putExtra method of intent, UserInfo objects writeToParcel method is called.

 

Intent intent = new Intent( this, UserAct.class );
intent.putExtra( “userinfo”, new UserInfo( “TestUserName”, 100 ) );

writeToParcel( Parcel dest, int flag ) method will accept following arguments dest of type Parcel and flag of type int.

dest: It is the Parcel to which the data of the UserInfo object must be written.
Flag: It is the int flag indicating how the data must be written to the Parcel.

To make sure that you are able to read back the UserInfo object, the UserInfo class must have a public static member “CREATOR” of type Parcelable.Creator<YourClass>. ( In this case YourClass must be replaced with UserInfo).

Following is the member method of Creator interface

public YourClass createFromParcel(Parcel in) {
//create an object of YourClass  and fill in the data by reading it
//from the Parcel

return new YourClass();
}

 

This method is called when you read the YouClass object back from the Intent.

To get the same object from the intent, you need to call the Intents getParcelableExtra method with the matching key.

UserInfo userInfo = intent.getParcelableExtra(“userinfo”);

Following Demo demonstrates the user of Parcelable

 

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:orientation=“vertical” >

 

<LinearLayout

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_marginLeft=“10dip”

android:layout_marginRight=“10dip”

android:layout_marginTop=“10dip”

android:gravity=“center_vertical” >

 

<ImageView

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:src=“@drawable/bitcode” />

 

<TextView

android:id=“@+id/textView1″

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_marginLeft=“30dip”

android:text=“Parcelable Demo”

android:textAppearance=“?android:attr/textAppearanceLarge” />

</LinearLayout>

 

<EditText

android:id=“@+id/edtUserID”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:hint=“User ID”

android:inputType=“numberDecimal” >

 

<requestFocus />

</EditText>

 

<EditText

android:id=“@+id/edtUserName”

android:layout_width=“match_parent”

android:layout_height=“wrap_content” />

 

<Button

android:id=“@+id/btnNext”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:text=“Write to Parcel and Start Next Activity” />

 

</LinearLayout>

 

 

MainActivity.Java

 

package in.bitcode.parcelabledemo; 

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

 

public class MainActivity extends Activity {

 

private EditText edtUserName, edtUserID;

private Button btnNext;

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

 

setContentView(R.layout.activity_main);

 

init();

 

btnNext.setOnClickListener(new View.OnClickListener() {

 

@Override

public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, UserAct.class);

 

String userName = edtUserName.getText().toString();

int userID = Integer.parseInt(edtUserID.getText().toString());

 

intent.putExtra(“userinfo”, new UserInfo(userName, userID));

 

startActivity(intent);

}

});

 

}

 

private void init() {

edtUserName = (EditText) findViewById(R.id.edtUserName);

edtUserID = (EditText) findViewById(R.id.edtUserID);

btnNext = (Button) findViewById(R.id.btnNext);

}

 

}

 

 

 

activity_useract.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:orientation=“vertical” >

 

<LinearLayout

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_marginLeft=“10dip”

android:layout_marginRight=“10dip”

android:layout_marginTop=“10dip”

android:gravity=“center_vertical” >

 

<ImageView

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:src=“@drawable/bitcode” />

 

<TextView

android:id=“@+id/textView1″

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_marginLeft=“30dip”

android:text=“Parcelable Demo”

android:textAppearance=“?android:attr/textAppearanceLarge” />

</LinearLayout>

 

<TextView

android:id=“@+id/txtUserID”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_marginTop=“10dip”

android:textSize=“20sp” />

 

<TextView

android:id=“@+id/txtUserName”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_marginTop=“10dip”

android:textSize=“20sp” />

 

</LinearLayout>

 

 

UserAct.java

 

package in.bitcode.parcelabledemo; 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.TextView;

 

public class UserAct extends Activity {

 

private TextView txtUserName, txtUserID;

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

 

init();

 

}

 

private void init() {

txtUserName = (TextView) findViewById(R.id.txtUserName);

txtUserID = (TextView) findViewById(R.id.txtUserID);

 

Intent intent = getIntent();

UserInfo userInfo = intent.getParcelableExtra(“userinfo”);

 

txtUserID.setText(“User ID: ” + userInfo.getUserID());

txtUserName.setText(userInfo.getUserName());

}

 

}

 

 

Download the Sample Demo of this app here ParcelableDemo.

 

Simple Animation Demo in Android, Using Multithreading

Hi All,
This is a sample application demonstrating how to Animate using AysncTask.
Ball class will draw itself by moving in a particular direction.
Ball class will hold it””””s radius, x y co-ordinates , color and the direction in which it should move. The move method of class Ball will manage the x,y co-ordinates depending on it””””s direction. The following is the class Ball .
———————————————————————————————————————–
package in.bitcode.animationdemo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
public class Ball {
    int x, y, r;
    Paint paint;
    String direction;
    public Ball( int x, int y, int r, int color, String direction ) {
        this.x = x; this.y = y; this.r = r;
        paint = new Paint();
        paint.setColor(color);
        this.direction = direction;
    }
    public void move(Canvas canvas ) {
        if( direction.equals(“up”) ) {
            y–;
        }
        if( direction.equals(“right”) ) {
            x++;
        }
        if( direction.equals(“down”) ) {
            y++;
        }
        if( direction.equals(“left”) ) {
            x–;
        }
        draw(canvas);
    }
    public void draw( Canvas canvas ) {
        canvas.drawCircle(x, y, r, paint);
    }
}

———————————————————————————————————————–

MyImageView class
MyImageview class is extending the class ImageView.
It will contain four Ball objects, initialized to move up, right, down and left. Their initial position will be center of the screen.  It””””s onDraw method is overridden which will call the move method on each ball by passing it the Canvas object.
We will be having a Thread which will invalidate this MyImageView after some interval so that the onDraw of MyImageView is called which will in turn call the move method on each ball contained inside it.
Following is the class MyImageView:

———————————————————————————————————————–
package in.bitcode.animationdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.widget.ImageView;

public class MyImageView extends ImageView {

Ball bup, bright, bdown, bleft;

public MyImageView(Context context, int width, int height ) {
super(context);
bup = new Ball( width/2, height/2, 20, Color.RED,”up”);
bright = new Ball( width/2, height/2, 20, Color.GREEN,”right”);
bdown = new Ball( width/2, height/2, 20, Color.BLUE,”down”);
bleft= new Ball( width/2, height/2, 20, Color.YELLOW,”left”);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
bup.move( canvas );
bright.move( canvas );
bdown.move( canvas );
bleft.move( canvas );
}

}
——————————————————

The Home class:

Home class extends the Activity class. Home activity class will create an object of class MyImageView and set it as content view. It will have and inner class MyThread which will be extending the class AsyncTask. MyThread will invalidate the MyImageView after certain interval.

Following is the Home class, it is containing an inner class Mythread:

————————————————
package in.bitcode.animationdemo;import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;public class Home extends Activity {

MyImageView view;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

view = new MyImageView(this, getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight() );
setContentView(view);

new MyBallThread().execute(null);

}

class MyBallThread extends AsyncTask<Object, Object, Object> {

@Override
protected Object doInBackground(Object… params) {
for( int i = 0; i < 200; i++ ) {
publishProgress(null);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}

@Override
protected void onProgressUpdate(Object… values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
view.invalidate();
}

}

}

————————————————

–  Android @ BitCode Technologies Pvt. Ltd. – No. 1 Mobile  Training Company in Pune

“Pioneers in Mobile Computing Training”

Find more about us at http://www.bitcode.in

Maintaining Global Application State through Android Application

Lots of time we need to maintain and share the Application state throughout the Application. We may need to share few strings or may be few global variables or few flags among activities and services and my be other application components.

In these scenarios the “Application” class will become handy.
The “Application” class can be extended and we can add the needed data members and methods to it, which help us to set and get the data across application components.

Following class is inherited from Application class, which holds an int and a string val.

class  MyApplication extends Application {
private int intData;
private String stringData;public void setIntData( int intData ) {
this.intData = intData;
}public void setStringData( String stringData ) {
this.stringData = stringData;
}

public int getIntData() {
return intData;
}

public String getStringData() {
return stringData;
}
}

Once you have got the Application class i.e. MyApplication class in this case, it has to be associated with your application. The “MyApplication” class is associated with your application through the “Android Manifest” file. Following snippet shows how to do it.

 <application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name” android:name=”.MyApplication” >
….
….

When your application starts executing an object of “MyApplication” class is created implicitly. This is object is available and will exist in memory throughout the application (till the time at least an activity of your app is available).
We can obtain a reference to the “MyApplication” object using the getApplicationContext() or getApplication() method.

Setting and Getting Data using the Application object

Now as we have set up the MyApplication class with the application, it is time to see how could we use it.
To demonstrate this we will be using two Activities. We well set data from one activity and will read the data from another activity.

Activity 1: ( In this Activity we will set the data)

….
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);MyApplication myApplication = (MyApplicaton) getApplicationContext();
// set some data
myApplication.setIntData( 101 );
myApplication.setStringData(“BitCode”);
// the data is set now, so you start new act now
}
….

Activity 2: (In this Activity we will read the data set by Activity 1)

 ….
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);MyApplication myApplication = (MyApplicaton) getApplicationContext();
// get the data back
int intData = myApplication.getIntData();
String stringData = myApplication.getStringData();
// do something with data as per your business logic
…..
}
….

This is how you can use the Application class and link it with your application to maintain and share the Global Application State in an Android Application.