Questions

Create Service in Android

Create Services in Android Application

Service ( android.app.Service ) is a class that run in background, not interact with user so this services we can use for Alarm Clock something else. The following way to create a services,

Step 1:- First you just create a standard the Activity, its a GUI for users, here we just call the service funtions to get the result, the code as follow,
package com.yos.yoscall;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class YosCall extends Activity {
/** Called when the activity is first created. */
public TextView t;
@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView ) findViewById(R.id.txtView);
t.setText("starting...");
try{
Monitor.setMainActivity(this);
}catch(Exception e){
t.setText(e.getMessage());
}
}
}


Step 2:- the main.xml, just create a textview only, the XML code should like






Step 3:- Need to create a class for Services, for example Monitor.java class, here extends the "Sevice" class also use the Timer class to run the programs frequent in background.
package com.yos.yoscall;


import java.util.*;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;

class Monitor extends Service {
private static final int PERIOD=1000;
private static YosCall YOS_CALL;
static long i=0;
private static Timer timer = new Timer();


@Override
public void onCreate() {
super.onCreate();
}

public static void setMainActivity(YosCall activity) {
YOS_CALL = activity;
YOS_CALL.t.setText("started!!");
_startService();
//SystemClock.sleep(PERIOD);
}

@Override
public IBinder onBind(Intent intent) {
return(null);
}

@Override
public void onDestroy() {
super.onDestroy();

}
public static void update(){
Date date = new Date();
i++;
YOS_CALL.t.setText( i + "::"+ date.toGMTString() );

}
private static void _startService() {
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
update();
}
},
0,
PERIOD);
}
}


Step 5

Build a Service


we need to create a service in the AndroidManifest.xml, the following code need to be added in the
Now, you run the application, it will run timer and increase "i" value in the background. Enjoy!!


Your Answers

Your Name:
Your Answers :
<> is a code tag
Preview
Enter the verification code:

Answers

josh
Jun 25 13 12:10:11
good one.there is a nice article about service here:
http://articlesforprogramming.blogspot.in/2013/06/how-to-create-service-in-android.html

robotprince
Sep 18 12 03:43:29
i had the same bug like Cynthia..Please tell me..Thanks!

Sekar
Oct 19 11 09:19:17
Which version of Android using on your mobile or emulator ?

Cynthia
Oct 19 11 03:28:56
Hi! I copied your code and it works fine except the app crashes after 5 seconds, any idea why this is happening?