Services Example:
In This Tutorial we will see how Services will execute;
OUT PUT Of The Tutorial:
OutPut:
In This Tutorial we will see how Services will execute;
OUT PUT Of The Tutorial:
Create Android Application:
- File >> New >> Android
Application
- Enter Project
name: ServicesApp
- Package: com.ambilpursunil.newapp
- Keep other
default selections, click Next until you reach Finish

1.Simply Copy and Past the Code which is display below in the MainActivity.java
package
com.ambilpursunil.newapp;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import
android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
boolean status = false;
Messenger mMessenger = null;
@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;
}
public void startMethod(View v){
if(status){
Toast.makeText(getBaseContext(), "Service
Already Started", Toast.LENGTH_LONG).show();
}else{
Intent
i = new Intent(this, MyService.class);
bindService(i,
sc, Context.BIND_AUTO_CREATE);
status = true;
Toast.makeText(getBaseContext(),
"Service Successfully Started", Toast.LENGTH_LONG).show();
}
}
public void stopMethod(View v){
if(status){
sc = null;
status = false;
Toast.makeText(getBaseContext(), "Service
Stopped", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(), "Service
Already Stopped", Toast.LENGTH_LONG).show();
}
}
public void invokeMethod(View v){
if(status){
Message
message = Message.obtain(null,1,0,0,0);
String
s = "This is the Message To the Client";
Bundle
bn = new
Bundle();
bn.putString("my_string", s);
message.setData(bn);
try {
mMessenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Toast.makeText(getBaseContext(), "Go
and Start Service First",Toast.LENGTH_LONG).show();
}
}
ServiceConnection sc = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Messenger = null;
}
@Overrid
public void onServiceConnected(ComponentName name, IBinder
service) {
// TODO Auto-generated method stub
mMessenger = new Messenger(service);
status = true;
}
};
}
2.Now Create Service class, right click on the src=>package=>New=>java class=>Name it as MyService.java Copy and Past the below code:
package com.ambilpursunil.newapp;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.widget.Toast;
public class MyService extends Service{
static final int SAY_HELLO = 1;
@Override
public IBinder
onBind(Intent intent) {
// TODO Auto-generated method stub
//This will return iBinder object to the client
return messenger.getBinder();
}
class
MessageHandler extends
Handler{
public void handleMessage(Message msg){
switch(msg.what){
case SAY_HELLO:
Toast.makeText(getBaseContext(),
"Hello From Service Class",Toast.LENGTH_LONG).show();
Bundle bn = msg.getData();
String message = bn.getString("my_string");
Toast.makeText(getBaseContext(), "Message:"+message,Toast.LENGTH_LONG).show();
break;
default:
super.handleMessage(msg);
}
}
}
Messenger messenger = new Messenger(new MessageHandler());
}
3.Simple Copy and Past the below code: actvitiy_main.xml
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ambilpursunil.newapp.MainActivity"
>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="67dp"
android:text="Strat Service"
android:onClick="startMethod"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Stop Service"
android:onClick="stopMethod"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Invoke Service+"
android:onClick="invokeMethod"
/>
</RelativeLayout>
4.Copy and past the code for manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ambilpursunil.newapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21"
/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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"></service>
</application>
</manifest>
5.Right click on the project and Run As-->Android Application
OUT PUT Of The Tutorial:
OutPut:
When our application launch it show three buttons when you click on Invoke Service+ Button you will get a Toast message like first go and start service when you click on Start Service get a Toast Service is Successfully started Now Click on Invoke Service+ button again then it will show all the Toast messges Like. Hello for service class and Message:This is the message to the client.
If you again click on Start Service button the a Toast like service already started .
Finally Go and click on Stop Service you get a Toast like Service Stopped.
Please Send Your Comments To ambilpura.sunil@gmail.com
Stay Tune For Next Tutorial... Services In Android:
No comments:
Post a Comment