Tuesday, May 17, 2011

Android Service

A Service is a Android Class used to run a process in background to avoid Application Not Responding errors.
Example:
Home.java:
package com.sercivedemo.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Home extends Activity
{
    Button btnStartService, btnStopservice;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnStartService = (Button)findViewById(R.id.btnStartService);
        btnStopservice = (Button)findViewById(R.id.btnStopservice);
       
        btnStartService.setOnClickListener(new OnClickListener()
        {          
            @Override
            public void onClick(View arg0)
            {
                startService(new Intent(Home.this, ServiceEx.class));
            }
        });
       
        btnStopservice.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                stopService(new Intent(Home.this, ServiceEx.class));
            }
        });
    }
}

ServiceEx.java:
package com.sercivedemo.activities;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class ServiceEx extends Service
{   
    Timer objTimer;
    @Override
    public void onCreate()
    {       
        super.onCreate();
        Log.e("Service :", "onCreate()");
       
        //Do the process here
     }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.e("Service :", "onDestroy()");
    }

    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        Log.e("Service :", "onStart()");
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}
main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
    <Button
        android:layout_width="wrap_content"
        android:id="@+id/btnStartService"
        android:text="StartService"
        android:layout_height="wrap_content">
    </Button>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnStopservice"
        android:text="StopService">
    </Button>   
   
</LinearLayout>

Android Launching Camera and attach the image to image view


public void takePhoto()
{
        //Intent to launch camara
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
       
        //Uri creattion to strore images
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+ "/" +   String.valueOf(System.currentTimeMillis())+ ".jpg"));
                   
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

        startActivityForResult(intent, 1);

}


protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
       super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
      
       if(requestCode == 1)
       {
           if(resultCode == RESULT_OK)
           {
                try
               {
                   ivPhoto.setBackgroundResource(0);
                   ivPhoto.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(new File(mImageCaptureUri.getPath()))));
               }
               catch (FileNotFoundException e)
               {               
                   e.printStackTrace();
               }
           }
           else if(resultCode == RESULT_CANCELED)
           {
               Log.d("Result: ", "Launch Cancelled.");
           }
     }
}

Call takePhoto() in the button click. 

Note: 

In the manifast.xml we have to add permissions.android.permission.WRITE_EXTERNAL_STORAGE

android.hardware.camera

Output: