I am developing android application in which I want to do some thing after every 10 sec. even application is closed.For that I implemented a background service which do background task for me.My code structure looks like:
// my main activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.serviceButton);
Button stop = (Button)findViewById(R.id.cancelButton);
start.setOnClickListener(startListener);
stop.setOnClickListener(stopListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
private OnClickListener stopListener = new OnClickListener() {
public void onClick(View v){
stopService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
//simpleservice
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}
This is working fine. But what I want to do now when I start service after every 10 sec just give me simple Toast message and when I stop service stop toast messages.
I also tried with AlarmManager.
// main activity....
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startAlert(View view) {
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (10 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + 10 + " seconds",
Toast.LENGTH_LONG).show();
}
// broadcast receiver
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panik but your time is up!!!!.",
Toast.LENGTH_LONG).show();
}
}
But I am not able to do it periodically. What is the proper way to implement this? Need help... Thank you...