How can I recall my android service after every 10 second.
This is my Service Class.
package com.example.vaccinationsystem;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class BackgroundServices extends Service{
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
}
I call this in some other class by:
startService(new Intent(this, BackgroundServices.class));
How can it will run after every 10 second.
try this AlarmManager
public void startTimer()
{
Log.i("timer Striii" , "timer is ");
Intent Service1 = new Intent(MainActivity.this , BackgroundServices.class);
PendingIntent piService1 = PendingIntent.getService(MainActivity.this , 0 , Service1 , PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager1 = (AlarmManager) MainActivity.this.getSystemService(Context.ALARM_SERVICE);
alarmManager1.cancel(piService1);
alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP , System.currentTimeMillis() , 16500 , piService1);
}
Related
I am attempting to create a background Service so when the application is closed a service is running in the background that will show a notification every 5 seconds to the phone using an AlarmManager.
I currently have my java service file setup as:
package com.racecoursedatatechnologies.rdtstockmanagement;
import android.app.Service;
import android.app.AlarmManager;
import android.content.Intent;
import android.util.Log;
import android.os.Binder;
import android.os.IBinder;
import android.app.PendingIntent;
import android.app.PendingIntent;
public class BackIntentService extends Service {
private PendingIntent pendingIntent;
private AlarmManager manager;
public class LocalBinder extends Binder {
BackIntentService getService() {
return BackIntentService.this;
}
}
#Override
public void onCreate() {
startAlarm();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
public void startAlarm()
{
manager = (AlarmManager)getSystemService(this.ALARM_SERVICE);
Intent intent = new Intent(this, BackNotifyAlarm.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
int interval = 1000 * 5;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// Tell the user we stopped.
Log.d("LocalService", "Stopped");
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
/**
* Show a notification while this service is running.
*/
private void showNotification() {
//Create a notification and set it's content and display it.
NotificationManager notif=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle("RDT Stock").setContentText("HELLOOO").
setContentTitle("Low Stock Items").setSmallIcon(R.drawable.noticon).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(11, notify);
}
}
BackNotifyAlarm Broadcast java file:
public class BackNotifyAlarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
//wl.acquire();
Toast.makeText(context, "Notification sent!", Toast.LENGTH_LONG).show();
//wl.release();
}
I am starting the service in the MainActivity file. The service starts and the service then runs an Alarm, however the alarm only seems to run once and not repeat, any idea why?
I am using this broadcast service with countdown timer. But when i kill the app, it is not ticking on same time(second), it is starts again.
Here is my code.
BroadcastService:
package com.example.emre.denemeprojesi;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.example.emre.denemeprojesi";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
System.out.println("STARTING TIMER");
cdt = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
Log.i(TAG, "Timer finished");
System.out.println("TIMER CANCELLED");
}
};
cdt.start();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Main Activity:
package com.example.emre.denemeprojesi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private String TAG ="Countdown Servisi";
private TextView lblResult ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblResult = (TextView)findViewById(R.id.lbl_result);
startService(new Intent(this, BroadcastService.class));
Log.i(TAG, "Started service");
}
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
#Override
public void onResume() {
super.onResume();
registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.i(TAG, "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(br);
Log.i(TAG, "Unregistered broacast receiver");
}
#Override
public void onStop() {
try {
unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
// stopService(new Intent(this, BroadcastService.class));
//Log.i(TAG, "Stopped service");
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
System.out.println(millisUntilFinished); //<<<bu göstermiyor<<<<<<
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
//
}
}
}
I'm supposed to add a timer to my service class that prints a message to LogCat every 10 seconds. Nothing in the service class is printing once I call the startService method and I have no idea why.. Any ideas?
package com.murach.reminder;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ReminderActivity extends Activity implements OnClickListener {
private Button startServiceButton;
private Button stopServiceButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
startServiceButton = (Button) findViewById(R.id.startServiceButton);
stopServiceButton = (Button) findViewById(R.id.stopServiceButton);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent(this, ReminderService.class);
switch (v.getId()) {
case R.id.startServiceButton:
// put code to start service and display toast here
startService(serviceIntent);
Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
break;
case R.id.stopServiceButton:
// put code to stop service and display toast here
stopService(serviceIntent);
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
break;
}
}
}
package com.murach.reminder;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class ReminderService extends Service
{
private Timer timer;
public void onCreate()
{
Log.d("Reminder", "Service created");
startTimer();
}
#Override
public IBinder onBind(Intent intent)
{
Log.d("Reminder", "No binding for this activity");
return null;
}
public void onDestroy()
{
Log.d("Reminder", "Service destroyed");
stopTimer();
}
private void startTimer() {
TimerTask task = new TimerTask() {
public void run() {
Log.d("Reminder", "Timer task executed");
}
};
timer = new Timer(true);
int delay = 1000 * 10;
int interval = 1000 * 10;
timer.schedule(task, delay, interval);
}
private void stopTimer()
{
if (timer != null)
{
timer.cancel();
}
}
}
And here is how I register the service in the Manifest (in a service element, it wouldn't let me type it out completely)
android:name="com.murach.reminder.ReminderService"
The package names do not match. There is a spelling mistake in the word murach in your Manifest declaration.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleAlarm(View V){
//Long time= new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
Long time= new GregorianCalendar().getTimeInMillis()+30*1000;
Intent intentAlarm= new Intent(this, AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for 30 repetd", Toast.LENGTH_LONG).show();
}
}
AlarmReceiverClass
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG);
}
}
This is my code i am trying to set alarm and display alarm message in each 30 second But i am unable to display Alarm messes in toast while i write code all the thing correct but i don't know where am doing mistake please look my code and please suggest me where am doing wrong .
First of all please add .show() in toast.
i.e. Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
EDIT
Please use the below code :
in manifest
<receiver android:name=".alarm.manager.Alarm" >
</receiver>
create a new class named AlarmService.java
public class AlarmService extends Service {
Alarm alarm = new Alarm();
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarm.SetAlarm(AlarmService.this);
return START_STICKY;
}
public void onStart(Context context, Intent intent, int startId) {
alarm.SetAlarm(context);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Another class alarm.java
package alarm.manager;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;
public class Alarm extends BroadcastReceiver {
public static final String ALARM_SERVICE = "alarm";
public Alarm() {
}
Context mContext;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressLint("NewApi")
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
mContext = context;
Log.d("App", "Alarm manager invoked");
wl.release();
}
public void SetAlarm(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1000, pi);
}
/**
* Stop alarm
*
* #param context
* = context of activity
*/
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
from your class call these lines
Alarm alarm = new Alarm();
alarm.SetAlarm(getApplicationContext());
You just missed to call .show() method for Toast. So it will be
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
I have mainActivity that starts service with START_STICKY onStartCommand, in that service I also use startForeground and alarmManager repeater. When I close the main activity by swiping the app away, service is still running, and the notification icon from the startForeground remains, however, when the alarm from the alarmManager sets off inside service, the service get crashed and restart itself within 5000 ms. Why does the service crash soon as it gets to setting of an alarm?
MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Messenger;
import android.util.Log;
public class MainActivity extends Activity {
Messenger mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckIfServiceIsRunning();
}
private void CheckIfServiceIsRunning() {
if (MyService.isRunning()) {
} else {
startService(new Intent(MainActivity.this, MyService.class));
}
}
#Override
protected void onDestroy() {
super.onDestroy();
//stopService(new Intent(MainActivity.this, MyService.class)); //disabled line so that killing UI-app doesn't kill service aswell
}
}
MyService.java:
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
public class MyService extends Service {
public AlarmManager alarmManager;
public PendingIntent pendingIntent;
private Timer timer = new Timer();
private int counter = 0, incrementby = 1;
private static boolean isRunning = false;
final public static int NOTIFICATION_FOREGROUND = 34444;
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
final Messenger mMessenger = new Messenger(new IncomingHandler());
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
#SuppressLint("HandlerLeak")
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
#Override
public void onCreate() {
super.onCreate();
Log.i("MyService", "---- Service Started. ----");
timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 1000L);
isRunning = true;
StartForegroundNotification();
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent broadcast_intent = new Intent(this, MyAlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, broadcast_intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pendingIntent);
}
#SuppressWarnings("deprecation")
public void StartForegroundNotification(){
String title = "Service Title";
String message = "Service Message";
Notification notify = new Notification(R.drawable.ic_launcher, null, 0);
Intent notifIntent = new Intent(this, MainActivity.class);
PendingIntent i = PendingIntent.getActivity(this, 0, notifIntent, 0);
notify.setLatestEventInfo(this, title, message, i);
notify.flags |= Notification.FLAG_NO_CLEAR;
startForeground(NOTIFICATION_FOREGROUND, notify);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
public static boolean isRunning()
{
return isRunning;
}
private void onTimerTick() {
Log.i("TimerTick", "Timer doing work." + counter);
try {
counter += incrementby;
} catch (Throwable t) {
Log.e("TimerTick", "Timer Tick Failed.", t);
}
}
#Override
public void onDestroy() {
super.onDestroy();
alarmManager.cancel(pendingIntent);
if (timer != null) {timer.cancel();}
stopForeground(true);
counter=0;
Log.i("MyService", "---- Service Stopped. ----");
isRunning = false;
}
}
MyAlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("alarmer", "I got it");
}
}
and in manifest I used:
<service android:name=".MyService" />
<receiver android:name=".MyAlarmReceiver" />
and the logcat (soon as it hit alarm time - after timer ticks 3 in this case - it crashed if the app is closed, however, after it restarts itself, it will not be crashed again, I guess because it's being started from different context, and not from MainActivity.this, it gets "null" intent in onStartCommand):
12-16 19:08:50.614: I/TimerTick(27069): Timer doing work.1
12-16 19:08:53.614: I/TimerTick(27069): Timer doing work.2
12-16 19:08:56.614: I/TimerTick(27069): Timer doing work.3
12-16 19:08:57.622: I/ActivityManager(395): Killing 27069:com.example.serviceexample/u0a10097: remove task
12-16 19:08:57.629: W/ActivityManager(395): Scheduling restart of crashed service com.example.serviceexample/.MyService in 5000ms
12-16 19:09:02.661: I/ActivityManager(395): Start proc com.example.serviceexample for service com.example.serviceexample/.MyService: pid=27100 uid=10097 gids={50097, 1028}
12-16 19:09:02.715: I/MyService(27100): ---- Service Started. ----
12-16 19:09:02.715: I/TimerTick(27100): Timer doing work.0
12-16 19:09:02.723: I/MyService(27100): Received start id 3: null