set schedule in android - android

I want to set a schedule in my application.
If my application is stopped by the application task killer, my application automatically runs after many seconds after it gets killed.
My application is like this :
public class AlarmServiceDemo extends Activity
{
/** Called when the activity is first created. */
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.startalarm);
Button buttonCancel = (Button)findViewById(R.id.cancelalarm);
buttonStart.setOnClickListener(new Button.OnClickListener()
{
// #Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(AlarmServiceDemo.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AlarmServiceDemo.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(AlarmServiceDemo.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
});
buttonCancel.setOnClickListener(new Button.OnClickListener()
{
//#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(AlarmServiceDemo.this, "Cancel!", Toast.LENGTH_LONG).show();
}
});
}
}
And this is my service :
public class MyAlarmService extends Service
{
#Override
public void onCreate()
{
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
}
#Override
public boolean onUnbind(Intent intent)
{
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
But my schedule doesn't work. How can I solved it?

you have to write exactly what you mean by starting application.If you want to start an Activity then you can write
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
Intent activityIntent = new Intent(context,
AlarmServiceDemo.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
super.onStart(intent, startId);
}

Related

Android Service again created after stopped once

i have created a simple service just periodically Toasting. But when service is stopped once it creates again by own and again continuously starting.
Following is my MainActivity code.
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, TestService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int i;
i=15;
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
i* 1000, pintent);
Button startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(getBaseContext(), TestService.class));
}
});
Button stopBtn = (Button) findViewById(R.id.stopBtn);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(new Intent(getBaseContext(), TestService.class));
}
});
}
Following is my service class
Testservice
public class TestService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Created", 1).show();
Log.i("TestService", "SERVICE START");
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
return super.onStartCommand(intent, flags, startId);
}
}
That's all my code when button clicked to stop service it once stopped but again created but it's own
what's I am doing wrong??
Thanks in advance..
Try to use START_STICKY :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
If its still not working, try returning START_REDELIVER_INTENT instead of START_STICKY.
Check this link for more information :
START_STICKY and START_NOT_STICKY
Try
MainActivity.this
instead of getBaseContext()
I have fixed my problem as My AlarmManager was periodically sending intent request to my service so I stopped service and also stopped my AlarmManger by alarm.cancel(pintent);
Thanks to all of you..

Android service is not running in my application

My service class not running in background i have followed the sample tutorial, dont what is the issue and why its not running?
This is my Service class
public class Services extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d("OnBind", "OnBind");
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("OnCreate", "OnCreate");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("OnStart", "OnStart");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
My Menifest
<service
android:name=".Services"
android:enabled="true" >
</service>
MyActivity to call the services
startService(new Intent(getApplicationContext(), Services.class));
Kindly look it out my coding and help me to run the app properly,
Thanks in Advance.
Check by providing the whole name of services class like com.example.Services rather than .Services in your manifest file.
For continiously running the service, do the following :
public class YourServiceName extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent i, int startId) {
this.test.run();
this.stopSelf();
}
public Runnable test= new Runnable() {
public void run() {
// Do something
}
};
}
The AlarmManager that starts it:
Intent testService = new Intent(this, YourServiceName .class);
PendingIntent pitestService = PendingIntent.getService(this, 0,testService,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pitestService);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pitestService);
Hope this helps.

Android AlarmManager problems

I'm making and application in android using multiple alarms, and i want to do differents things for each alarm, my problem is that i don't know how to recover the id of the alarm or differentiate each alarm in alarm class.
This is my code:
//Activate the alarm
public void ActivateAlarm(int num) {
int seconds =Preferences.getTime(num);
myIntent[num] = new Intent(Settings.this,
Alarm.class);
pendingIntent[num] = PendingIntent.getService(Settings.this, num,
myIntent[num], 0);
alarmManager[num] = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager[num].setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
seconds * 1000, pendingIntent[num]);
Toast.makeText(Settings.this, "Alarm"(num+1)+"activated",Toast.LENGTH_LONG)
.show();
}
class Alarm
public class Alarm extends Service implements Runnable {
public int alarmID;
private static Thread thread;;
#Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(1);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Toast.makeText(Alarm.this, Alarm.thread.getName(), Toast.LENGTH_LONG).show();
//ReadFile.readFile(Integer.parseInt(thread.getName()));
displayNotification();
}
};
private void displayNotification() {
//different notification for each alarm
}
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
//super.onStart(intent, startId);
thread = new Thread(this);
thread.start();
}
public void setIDAlarm(int pos){
this.alarmID=pos;
}
}
Thank you.
SInce it worked for you i'll post as answer for others:
You can use
intent.setAction("MyAction1")
and then filter your alarms with
intent.getAction().equals("MyAction1") { do something ...}

How to auto Trigger Alarm Manager on its own instead of onClick

Below is my code which is working very fine. I am calling service after 10 seconds on click of button using Alarm Manager. I want to automate this process say every 10 minutes it should trigger on its own and call service irrespective of device in SCREEN_OFF or SCREEN_ON. Currently i also suspect call is from "Activity" due to which if I close the application it would not trigger.
/*MainActivity.java*/
package com.example.alarmservice;
public class MainActivity extends Activity implements OnClickListener{
final static private long ONE_SECOND = 1000;
final static private long TEN_SECONDS = ONE_SECOND * 10;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
findViewById(R.id.the_button).setOnClickListener(this);
}
private void setup() {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
}
};
registerReceiver(br, new IntentFilter("com.example.alarmservice"));
//pi = PendingIntent.getBroadcast( this, 0, new Intent("com.authorwjf.wakeywakey"),0);
//am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
Intent intent = new Intent(MainActivity.this, ServiceClass.class);
pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + TEN_SECONDS, pi);
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
}
Service Class
/*ServiceClass.java*/
package com.example.alarmservice;
public class ServiceClass extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("Testing", "Service got created");
Toast.makeText(this, "ServiceClass.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show();
Log.d("Testing", "Service got started");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

Service Stopping in Android

I have Android Service that runs always in background, and another service which is triggered by the always running service which is alarmmanager service.
Howewer, I want to stop service with a button, my aim is to stop always running service so the alarm manager service will automatically be stopped. Is it correct perspective?
My sample code is as follows
package com.example.deneme;
public class AndroidNotifyService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartService = (Button)findViewById(R.id.startservice);
Button buttonStopService = (Button)findViewById(R.id.stopservice);
buttonStartService.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(AndroidNotifyService.this, com.example.deneme.AndroidScheduledService.class);
AndroidNotifyService.this.startService(intent);
}});
buttonStopService.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(AndroidScheduledService.ACTION);
intent.putExtra("RQS", AndroidScheduledService.RQS_STOP_SERVICE);
sendBroadcast(intent);
}});
}
}
My always running service
package com.example.deneme;
public class AndroidScheduledService extends Service {
final static String ACTION = "AndroidScheduledServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getBaseContext(),
MyScheduledReceiver.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(getBaseContext(),
0, myIntent, 0);
AlarmManager alarmManager
= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//this.unregisterReceiver(notifyServiceReceiver);
Intent intent = new Intent();
intent.setAction(NotifyService.ACTION);
intent.putExtra("RQS", NotifyService.RQS_STOP_SERVICE);
sendBroadcast(intent);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
My Alarmmanager service
public class NotifyService extends Service {
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
HttpClient httpclnt;
HttpPost httppst;
String message;
String response;
//NotifyServiceReceiver notifyServiceReceiver;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";
/*
#Override
public void onCreate() {
// TODO Auto-generated method stub
notifyServiceReceiver = new NotifyServiceReceiver();
super.onCreate();
}
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
/*
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(notifyServiceReceiver, intentFilter);
*/
// Send Notification
notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher,
"Notification!",
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Exercise of Notification!";
String notificationText = "http://www.google.com/";
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent
= PendingIntent.getActivity(getBaseContext(),
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//this.unregisterReceiver(notifyServiceReceiver);
super.onDestroy();
}
/*
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class NotifyServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int rqs = arg1.getIntExtra("RQS", 0);
if (rqs == RQS_STOP_SERVICE){
stopSelf();
}
}
}*/
}
My BroadCast Receiver Classes
For NotifyService Class
package com.example.deneme;
public class MyScheduledReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(context, com.example.deneme.NotifyService.class);
context.startService(intent2);
}
}
For AndroidScheduledService Class
package com.example.deneme;
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
Intent myIntent = new Intent(context, com.example.deneme.AndroidScheduledService.class);
context.startService(myIntent);
}
}
}
Stopping the service won't stop the Alarm manager service. You have to stop it manually.
Intent intent = new Intent(this, com.example.deneme.AndroidScheduledService.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
To stop a service:
Intent stopServiceIntent = new Intent(getBaseContext(), yourServiceToStop.class);
getBaseContext().stopService(stopServiceIntent );

Categories

Resources