Your Open Source

Mobile  >>  Android

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!!


  • hits 1245
  • datetime Sep 09 09 04:06:15
  • author Sekar
  • rating

Rating : 12345
Tags :- Android

Answers

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