Saturday, 10 August 2013

Commonly asked Android permissions in interview:

 android.permission.READ_CONTACTS-----à Allows an application to read (but not read) the user's contacts data
android.permission.WRITE_CONTACTS-----à Allows an application to write (but not read) the user's contacts data
android.permission.READ_EXTERNAL_STORAGE-------à Allows an application to read from external storage
android.permission.WRITE_EXTERNAL_STORAGE------à Allows an application to write to external storage
android.permission.CAMERA-------à Required to be able to access the camera device.
android.permission.BLUETOOTH---------à Allows applications to connect to paired bluetooth devices
android.permission.BLUETOOTHADMIN----------à Allows applications to discover and pair bluetooth devices
android.permission.READ_PHONE_STATE---------à Allows read only access to phone state.
android.permissio.MODIFY_PHONE_STATE-------à Allows modification of the telephony state - power on, mmi, etc.
android.permission.ACCESS_FINE_LOCATION--------à Allows an application to access fine (e.g., GPS) location
android.permission.ACCESS_COARSE_LOCATION--------à Allows an application to access coarse (e.g., Cell-ID, WiFi) location
android.permission.ACCESS_NETWORK_STATE---------à Allows applications to access information about networks
android.permission.ACCESS_WIFI_STATE------------à Allows applications to change Wi-Fi connectivity state
android.permission.PROCESS_OUTGOING_CALLS--------------à Allows an application to monitor, modify, or abort outgoing calls.
android.permission.BATTERY_STATS----------à Allows an application to collect battery statistics
android.permission.CALL_PHONE---------à Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.
android.permission.CHANGE_NETWORK_STATE----------à Allows applications to change network connectivity state
android.permission.CHANGE_WIFI_STATE----------à Allows applications to change Wi-Fi connectivity state
android.permission.DISABLE_KEYGUARD---------à Allows applications to disable the keyguard
android.permission.FLASHLIGHT-------------à Allows access to the flashlight
android.permission.INTRNET------------à Allows applications to open network sockets.
android.permission.READ_SMS-------------à Allows an application to read SMS messages
android.permission.RECORD_AUDIO-----------à Allows an application to record audio
android.permission.RECEIVE_MMS-----------à Allows an application to monitor incoming MMS messages, to record or perform processing on them.
android.permission.RECEIVE_SMS------------à Allows an application to monitor incoming SMS messages, to record or perform processing on them
android.permission.SET_WALLPAPER-----------à Allows applications to set the wallpaper

android.permission.VIBRATE-----------à Allows access to the vibrator

Friday, 9 August 2013

Vibrate Phone In A Pattern

To Vibrate Phone in a Pattern we need to specify the pattern as long array
for Ex.

   long pattern[]={0,800,200,1200,300,2000,400,4000}

this is pattern in which we want to Vibrate the Phone
first 0  means silent for 0 milisecond
next 800 means vibrate for 800 milisecond
next 200 means  silent for 200 milisecond
next 1200  means vibrate for 1200 miliseconds, and so on.


To vibrate a phone we need following Permission Do not forget to declare this permission in Manifest.

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

We can Vibrate a Phone Using an Activity  , Service and Using Threads.

Using Activity will not be a good Idea because it takes time to vibrate the Phone and an Activity always runs in foreground.

We will implement using Service because  a Service runs in Background.

for we need to have an Object of Class Vibrator, we do not create the Object directly but we get Vibrate System Service.

Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

Add    <uses-permission android:name="android.permission.VIBRATE"/>  in Your Manifest

So let's start.

Create a new Android Project  "Vibrate Phone".
and edit the manifest and main.xml file

manifest file


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjuncture.vibrate"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".VibrateMainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- Declare the Vibrate Service -->
        <service android:name=".VibrateService"/>
        
    </application>

</manifest>

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:background="#99C2D6"
    android:orientation="vertical">
    
    

    <TextView
        android:layout_marginTop="140dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Android Vibrate Service Example" />

    <Button
        android:id="@+id/buttonVibrate"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Vibrate" />
    
</LinearLayout>

When User clicks on Vibrate Button we will start a new Service which will vibrate the phone.

VibrateMainActivity .java

public class VibrateMainActivity extends Activity 
{

     @Override
     public void onCreate(Bundle savedInstanceState)
     {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
    
     Button btnVibrate=(Button)findViewById(R.id.buttonVibrate);
    
    
     // Set on click listener and start vibrate service when clicked on Button Vibrate
    
     btnVibrate.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub

// Create a New Intent and start the Service
Intent intentVibrate =new Intent(getApplicationContext(),VibrateService.class);
startService(intentVibrate);

}
});
     }

   
}






And The Service Class

Do Not Forget To Declare the Service in Manifest like
<service android:name=".VibrateService"/>

public class VibrateService  extends Service
{

   

           @Override
            public void onStart(Intent intent, int startId) 
           {
                // TODO Auto-generated method stub
                super.onStart(intent, startId);
               
                       
                       
                                    Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

                                 
                                   // If you want to vibrate  in a pattern
                                     long pattern[]={0,800,200,1200,300,2000,400,4000};
                                   // 2nd argument is for repetition pass -1 if you do not want to repeat the Vibrate
                                    v.vibrate(pattern,-1);

                                  Toast.makeText(getApplicationContext(), "Phone is Vibrating", Toast.LENGTH_LONG).show();
                             }

        @Override
        public IBinder onBind(Intent intent)
        {
            // TODO Auto-generated method stub
            return null;
        }
      
}

Point To Note:


   long pattern[]={0,800,200,1200,300,2000,400,4000}

this is pattern in which we want to Vibrate the Phone
first 0  means silent for 0 milisecond
800 means vibrate for 800 milisecond
200 means  means silent for 200 milisecond
1200  means vibrate for 1200 miliseconds


Thursday, 8 August 2013

Brief description of ANR (Application Not Responding) and how to investgate

ANR(Application Not Responding)
ANR is actually a dialog that appears to the user whenever an application have been unresponsive for a long period of time or when some long operation takes place in the "main" thread.


so, how to diagnose the problem, it's easy,

adb shell cat/data/anr/traces.txt

the syntax will drump all the application not responding traces to the command prompt.(make sure to change the command promt buffer size otherwise you can not see the full log out)

Android will display the ANR dialog for a particular application when it detects one of the following conditions:
1. No response to an input event(such as a key press or screen touch events) within 5 seconds.
2. A BroadcastReceiver hasn't finished executing within 10 seconds.
3.if your application is doing work in the the background in response to user input, show that progress is being made(such as with a progressBar in your UI).

StrictMode:

You should avoid performing long running operations on the UI thread. This includes file and network access.
To ensure this you can use StrictMode. StrictMode is available as of API 9 (Android 2.3.3) and allows to setup thread policies for your application.
Via StrictMode you can instruct the Android system to crash your application if it performs long running operations, e.g. I/O in the user interface thread.
The following code shows how to use StrictMode. As the activity violates these settings it will crash.
package de.vogella.android.strictmode;
 
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
 
public class TestStrictMode extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Activate StrictMode
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork() 
         // alternatively .detectAll() for all detectable problems
        .penaltyLog()
        .penaltyDeath()
        .build());
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
         .detectLeakedSqlLiteObjects()
         .detectLeakedClosableObjects()
        // alternatively .detectAll() for all detectable problems
        .penaltyLog()
        .penaltyDeath()
        .build());
    
    // Test code
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String eol = System.getProperty("line.separator");
    try {
      BufferedWriter writer = 
          new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile", 
              MODE_WORLD_WRITEABLE)));
      writer.write("This is a test1." + eol);
      writer.write("This is a test2." + eol);
      writer.write("This is a test3." + eol);
      writer.write("This is a test4." + eol);
      writer.write("This is a test5." + eol);
      writer.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
} 
StrictMode should only be used during development and not in your live application.

using penaltyLog() you can watch the output of adb logcat while you use your application to see the violation as they happen.

Android Services vs Background Threads

A question that is asked by many new Android developers is when to use a service and when to use a background thread for some task that threatens to block the UI thread. This question is somewhat misleading because it suggests that the two options are mutually exclusive. Before attempting an answer to the question we first have to know a little about who Android works with threads.
Android’s Main Thread
When an application is started in Android the system will create a single thread for that application. This thread is called the main thread or sometimes also the UI thread. It has to be noted that the UI thread does not only handle UI tasks. That is why I prefer the name main thread, although I will sometimes use the term UI thread as well.
Among other things, the main thread is responsible for starting the application, i.e. for calling the Application.onStart() method. The name UI thread is justified in the sense that performing longer tasks on this thread means blocking the user interface. For this reason, anything that is computationally more intensive or might take longer for other reasons should be carried out in a thread separate from the main thread.
Background Threads
Creating threads in Android is essentially the same as in any other Java application. You can implement the Runnable interface and you can pass it to a Thread to execute. The question that arises is where the thread should be managed.
Activity Scope:
For many tasks you can simply manage the thread in the Activity. Depending on your requirements, you can start the thread in the
 Activity.onStart() method and cancel it in the Activity.onStop() method. Alternatively you can use the Activity.onCreate() and Activity.onDestroy() methods for managing the threads.
Application Scope:
Sometimes your thread needs to run across your whole application. That means it should stay alive even if the user navigates from one Activity to the next. In this case it is better to manage the thread in an application wide context.  One way of doing this is to extend the Application class and override its onCreate() method to start a worker thread. Another alternative is to use singletons.
Services
Android beginners often assume that services run in a separate thread because they are designed to run background tasks. This is not the case! By default a service will be called on the main thread. This confusion often arises because the main thread is referred to as UI thread and services are supposed to run in the background.
If you are doing complex tasks within services then you must create a worker thread within that service. A service is not an alternative to background threads but it provides another scope in which to run your worker threads! You should always create a separate thread within a service if you are doing something more complicated.
The Service class differs from the previous scopes by its life cycle. Implementing a service tells the Android system that the thread should stay alive, even when the user is not interacting with the application. In addition, a Service can be started from another application using an Intent. If neither of these two properties is required by your background task then you should not use a Service but a background thread in another context.
Managing Threads
In all of the above cases, worker threads are not managed by the Android system and you should terminate them when they are no longer needed. This means that a thread that is created in Activity.onStart() should be terminated in Activity.onStop(). Otherwise you will be creating new threads every time that the activity starts, resulting in leaking threads. This can be extremely devastating for performance.
Summary
The opening question, whether to use a service or a background thread is not an either/or question. Whenever you have a longer task to perform you should delegate it to a worker thread. The question should really be:
“Who should be managing the worker thread?”

The answer depends on the type of task. A thread managed by the activity should terminate when the activity stops or is destroyed. A thread managed inside the Application class or inside another global application-wide object can  perform background tasks across multiple activities. Managing a worker thread in a service tell the Android system that it wants to stay alive, even when there is no user interaction with the application.