Jun 12, 2014

Android Backgound Processing Service

This Example Show How To Use Services In Android.Our Main Task In This Example Is Start A Service and End A Service.A Service Is A Component That Runs In The Background To Perform Long-Running Operations Without Any Interact With The User.

First Of All We Need To Create A New Android Application Project.In My Case I'm Calling My Application As 'BackgroundService'.The Start up Window Appear As Below.





After Creating The Application We Have To Design Our Layout With Two Buttons.In My Case Im Calling My Buttons As 'Start Service' & 'End Service'.In Order To Do That Open The 'activity_main.xml' File.Replace The File With Following Codes.



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/start_service"
    android:onClick="startService"/>

   <Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/stop_service"
    android:onClick="stopService" />

</LinearLayout>


After Adding This Codes You Will Get Few Errors.Don't Worry About It.Errors Are Coming Because Because We Didn't Add The Strings to strings.xml File.In Order To Do That Go To res --> values --> strings.xml And Add The Two Strings As Follows.


<resources>
    <string name="app_name">HelloWorld</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="start_service">Start Service</string>
    <string name="stop_service">Stop Service</string>
</resources>





Now We Have Our Layout and We Need To Create Service Class.In Order To Create Service Class Right Click The 'src' Folder & Go To New --> Class.It Will Open You A New Window To Create A New Class.Give The Class Name,Make The Class As Public Too.In My Case I'm Calling My Service Class As 'MyService'. 


package com.example.backgroundprocess;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
   @Override
   public IBinder onBind(Intent arg0) {
      return null;
   }

   @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}


Now We Have To Call This Service To Start.In Order To Do That We Have To Add Few Code Lines To 'MainActivity.java'.


package com.example.backgroundprocess;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // Method to start the service
    public void startService(View view) {
       startService(new Intent(getBaseContext(), MyService.class));
    }

    // Method to stop the service
    public void stopService(View view) {
       stopService(new Intent(getBaseContext(), MyService.class));
    }
}

Change Manifest To Identify The Service.Add Following Code In AndroidManifest File In Between "</activity>" &  "</application>" Tags As Follows.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.backgroundprocess"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="9" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.backgroundprocess.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />
    </application>

</manifest>


Now We Have Completed Our Coding Parts.Now Run The Application & See.After Clicking 'Start Service' You Will Get The Out Put As Below.






Now Press The 'Stop Service' Button.You Will Get The Following Output.





Now You Can Use This Is Simple Application As A Component To Your Application. 
For Your Knowledge : You Can Start A Services Many Time Without Even Stopping It.But You Can Only Stop A Service If Their Is A Running Service Only.

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...