Android Studio AlarmManager Background Repeat Run - android

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?

Related

Unable to display Alarm messge when alarm is set

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();

How to stop audio playback when a phone call arrives in Android

hello im new to android and im doing a simple online radio app for my church the poblem is that i need the playback service to stop and restart when the phone gets a call and end it
so far i can stop the service just fine but when it gets started again just crashes so i dont know what im doing wrong
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.IBinder;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.NotificationCompat;
import com.spoledge.aacdecoder.MultiPlayer;
public class RadioService extends Service{
WakeLock wakelock;
//TelephonyManager teleManager= null;
//PhoneStateListener listener;
NotificationManager mNotificationManager;
public static MultiPlayer aacPlayer;
public static String radio;
private static Boolean isTuning;
// private TeleListener myListener = null;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
setTuning(false);
setRadio(getString(R.string.rhema));
aacPlayer = new MultiPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
setTuning(true);
setTuning(true);
aacPlayer.playAsync(radio);
//CallReceiver.setTuning(true);
Resources r= getResources();
String[] Notify = r.getStringArray(R.array.PlayNotify);
// prepare intent which is triggered if the
// notification is selected
Intent inten = new Intent(this, PlayerActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, inten, 0);
// build notification
// the addAction re-use the same intent to keep the example short
NotificationCompat.Builder n = new NotificationCompat.Builder(this)
.setContentTitle(Notify[0])
.setContentText(Notify[1])
.setSmallIcon(R.drawable.noti_icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pIntent);
Notification hola = n.build();
startForeground(100, hola);
//startForeground(startId, notification);
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
pause();
//CallReceiver.setTuning(false);
super.onDestroy();
}
public static boolean getTuning() {
return isTuning;
}
public void setTuning(boolean Tuning) {
isTuning = Tuning;
}
public void setRadio(String r){
radio = r;
}
public void PlayNotify(){
Resources r= getResources();
String[] Notify = r.getStringArray(R.array.PlayNotify);
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, RadioService.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
NotificationCompat.Builder n = new NotificationCompat.Builder(this)
.setContentTitle(Notify[0])
.setContentText(Notify[1])
.setSmallIcon(R.drawable.noti_icon)
.setContentIntent(pIntent)
.setAutoCancel(true);
n.setOngoing(true);
n.setContentIntent(pIntent);
//NotificationManager mNotificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(100, n.build());
}
public static void play(){
aacPlayer.playAsync(radio);
}
public static void pause(){
aacPlayer.stop();
}
}
and this is the broadcast
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class CallReceiver extends BroadcastReceiver{
TelephonyManager telManager;
Context context;
public static boolean Tuning = false;
PlayerActivity mainActivity;
NotificationManager mNotificationManager;
#Override
public void onReceive(Context context, Intent intent) {
mainActivity=new PlayerActivity();
this.context=context;
telManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private final PhoneStateListener phoneListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: {
//PAUSE
if(Tuning){
context.stopService(new Intent(context,RadioService.class));
}
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK: {
if(Tuning){
context.stopService(new Intent(context,RadioService.class));
}
break;
}
case TelephonyManager.CALL_STATE_IDLE: {
//PLAY
if(Tuning){
showNotification(context);
context.stopService(new Intent(context,RadioService.class));}
break;
}
default: { }
}
} catch (Exception ex) {
}
}
};
public static void setTuning(boolean r){
Tuning = r;
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, PlayerActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti_icon)
.setContentTitle("Rhema Stereo")
.setContentText("Vuelve a Sintonizarnos.");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());}
}
the weir thing is that from the activities i can start and stop the service just fine but here i can only stop it. So for now im using a notification to get back to an activity and restart the service
If I may, I would suggest another approach for this problem. You state that:
i need the playback service to stop and restart when the phone gets a
call
However, the issue is more complex. You should also stop playback, for example, when a notification arrives, or if another music player is started by the user. Instead of having to monitor all these posibilities independently, Android provides built-in support for this concept -- it's called the audio focus. In broad terms, it means that only one app can have audio focus at one point in time, and that you should relinquish if it asked to.
This behavior can be obtained by using an OnAudioFocusChangeListener.
Basically, you must:
Request audio focus before starting playback.
Only start playback if you effectively obtain it.
Abandon focus when you stop playback.
Handle audio focus loss (either by lowering volume or stopping playback altogether).
Please check the Managing Audio Focus article in the Android documentation.
you need to add this snippet in your current activity
IntentFilter receiverFilter = new IntentFilter(
Intent.ACTION_HEADSET_PLUG);
BootBroadcast receiver = new BootBroadcast();
registerReceiver(receiver, receiverFilter);
then the same need to register in the receiver manifest.xml
eg:
<receiver
android:name="YOUR_ACTION_STRING.BootCompletedReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Also add this flag inside BootBroadcast class
newIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Recall Android Services

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);
}

Android Notification showing only once

I have the following code in which I have one date picker and time picker
When I select that date and time I want to show notification...
It is perfectly working but when I again put notification means if I pu6 multiple notification it will show me only last one...
Means only last notification is showing not all...
NotifyService.java
package com.blundell.tut.service;
import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.blundell.tut.ui.phone.SecondActivity;
public class NotifyService extends Service {
/**
* Class for clients to access
*/
public class ServiceBinder extends Binder {
NotifyService getService() {
return NotifyService.this;
}
}
// Unique id to identify the notification.
public static int NOTIFICATION = 123;
// Name of an intent extra we can use to identify if this service was started to create a notification
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public void onCreate() {
Log.i("NotifyService", "onCreate()");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// If this service was started by out AlarmTask intent then we want to show our notification
if(intent.getBooleanExtra(INTENT_NOTIFY, false))
showNotification();
// We don't care if this service is stopped as we have already delivered our notification
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients
private final IBinder mBinder = new ServiceBinder();
/**
* Creates a notification and shows it in the OS drag-down status bar
*/
private void showNotification() {
// This is the 'title' of the notification
CharSequence title = "Alarm!!";
// This is the icon to use on the notification
int icon = R.drawable.ic_dialog_alert;
// This is the scrolling text of the notification
CharSequence text = "Your notification time is upon us.";
// What time to show on the notification
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, text, time);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SecondActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title, text, contentIntent);
// Clear the notification when it is pressed
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
NOTIFICATION++;
Toast.makeText(NotifyService.this, Integer.toString(NOTIFICATION), Toast.LENGTH_SHORT).show();
mNM.notify(NOTIFICATION, notification);
// Stop the service when we are finished
stopSelf();
}
}
ScheduleClient.java
package com.blundell.tut.service;
import java.util.Calendar;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
/**
* This is our service client, it is the 'middle-man' between the
* service and any activity that wants to connect to the service
*
* #author paul.blundell
*/
public class ScheduleClient {
// The hook into our service
private ScheduleService mBoundService;
// The context to start the service in
private Context mContext;
// A flag if we are connected to the service or not
private boolean mIsBound;
public ScheduleClient(Context context) {
mContext = context;
}
/**
* Call this to connect your activity to your service
*/
public void doBindService() {
// Establish a connection with our service
mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
/**
* When you attempt to connect to the service, this connection will be called with the result.
* If we have successfully connected we instantiate our service object so that we can call methods on it.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
/**
* Tell our service to set an alarm for the given date
* #param c a date to set the notification for
*/
public void setAlarmForNotification(Calendar c){
mBoundService.setAlarm(c);
}
/**
* When you have finished with the service call this method to stop it
* releasing your connection and resources
*/
public void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
mContext.unbindService(mConnection);
mIsBound = false;
}
}
}
ScheduleService.java
package com.blundell.tut.service;
import java.util.Calendar;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.blundell.tut.service.task.AlarmTask;
public class ScheduleService extends Service {
/**
* Class for clients to access
*/
NotifyService ns=new NotifyService();
public class ServiceBinder extends Binder {
ScheduleService getService() {
return ScheduleService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ScheduleService", "Received start id " + ns.NOTIFICATION + ": " + intent);
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
private final IBinder mBinder = new ServiceBinder();
/**
* Show an alarm for a certain date when the alarm is called it will pop up a notification
*/
public void setAlarm(Calendar c) {
// This starts a new thread to set the alarm
// You want to push off your tasks onto a new thread to free up the UI to carry on responding
new AlarmTask(this, c).run();
}
}
AlarmTask.java
package com.blundell.tut.service.task;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.blundell.tut.service.NotifyService;
public class AlarmTask implements Runnable{
// The date selected for the alarm
private final Calendar date;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
public AlarmTask(Context context, Calendar date) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.date = date;
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), pendingIntent);
long firstTime = date.getTimeInMillis();
am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, am.INTERVAL_DAY * 7, pendingIntent);
}
}
MainActivity.java
package com.blundell.tut.ui.phone;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
import com.blundell.tut.R;
import com.blundell.tut.service.NotifyService;
import com.blundell.tut.service.ScheduleClient;
public class MainActivity extends Activity
{
// This is a handle so that we can call methods on our service
private ScheduleClient scheduleClient;
private DatePicker picker;
NotifyService ns;
private TimePicker tp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleClient = new ScheduleClient(this);
scheduleClient.doBindService();
ns=new NotifyService();
picker = (DatePicker) findViewById(R.id.scheduleTimePicker);
tp=(TimePicker)findViewById(R.id.TimePicker);
tp.setIs24HourView(true);
}
public void onDateSelectedButtonClick(View v){
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
int hour=tp.getCurrentHour();
int min=tp.getCurrentMinute();
// Create a new calendar set to the date chosen
// we set the time to midnight (i.e. the first minute of that day)
Calendar c = Calendar.getInstance();
c.set(year, month, day,hour,min,0);
scheduleClient.setAlarmForNotification(c);
// Notify the user what they just did
//Toast.makeText(this, Integer.toString(ns.NOTIFICATION), Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Notification set for: "+ day +"/"+ (month+1) +"/"+ year, Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop()
{
// When our activity is stopped ensure we also stop the connection to the service
// this stops us leaking our activity into the system *bad*
if(scheduleClient != null)
scheduleClient.doUnbindService();
super.onStop();
}
}
SecondActivity.java
package com.blundell.tut.ui.phone;
import android.app.Activity;
import android.os.Bundle;
import com.blundell.tut.R;
/**
* This is the activity that is started when the user presses the notification in the status bar
* #author paul.blundell
*/
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
Please suggest me at which place i have to change code...????
In this line,
mNM.notify(NOTIFICATION, notification);
Just make sure that each time the different value of NOTIFICATION is being passed.
at AlarmTask.java, you are hard coded always 0 in PendingIntent.
requestCode must be
UNIQUE INTEGER NUMBER
so change your code,
from
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
to
int random = (int)System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, random, intent, 0);
Just write code like this.
int random = (int)System.currentTimeMillis();
manager.notify(random , activeNotification);

Service crash, even with startForeground when the activity gets shut down and the alarmManager sets off

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

Categories

Resources