Tuesday, October 13, 2015

How to print Toast repeat it after 5 second from Service Running in background in android

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 MyService  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 .
    timer = new Timer();
    timer.schedule(new TimerTask() {
    @Override    public void run() {
        ///////////// Checking Running application After 5 Second again///////////////       RepeatWork();
        ///////schedule the timer, after the first 5000ms the TimerTask will run every 1000ms    }
}, 5000, 5000);
        return START_STICKY;     }
public void RepeatWork(){
Toast.makeText(getBaseContext(), " Hellow Shohan !", Toast.LENGTH_SHORT).show();
}
}

No comments:

Post a Comment