Monday, August 10, 2015

How to Service Running in background in android

1. First create a class  and extends  Service like
 public class MyService extends Service {}
2.Secondly include method in service class like 
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onCreate() {
    super.onCreate();
}
@Override
public void onDestroy() {
    super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// this method keep running service in bacground
return START_STICKY;
}
3.Thirdly include the MyService in manifest   like :
<service
    android:name="MyService"
    android:enabled="true"
    android:label="check Running Apps" />
4.Finally start the service when you want to start like:
startService(new Intent(this, MyService.class)); 
I start service in the following time
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(this, MyService.class));
  }
5. When you want to stop the service just use this
stopService(new Intent(this, second_ MyService.class));
6. Fully service class like bellow :
public class second_Service extends Service {
    Timer timer;
    SharedPreferences appData;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

// write  your code , that you want to active  in backgrount in your application .
        return START_STICKY;
    }
}

No comments:

Post a Comment