I start a repeat task in AlarmManager,but how can i get the repeat counts in service.
here is code
MyActivity
mAlarmSender = PendingIntent.getService(MyActivity.this,0, new Intent(MyActivity2.this, AutoBuild.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 1000 * 5, mAlarmSender);
AutoBuild
public class AutoBuild extends Service {
private String[] infos;
private Intent mIntent;
private String pathStr;
static final String TAG = "AutoBuild";
private int i=0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.mIntent = intent;
return START_STICKY;
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
printData(i);/**print result*/
i++;/*count ++*/
AutoBuild.this.stopSelf();/*stop service */
}
private void printData(int i) {
Log.i(TAG, i + "");
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
the value of i always 0:Is there anyway can change this value when Alarmanage repeat
The thing with Service is that it runs as a single instance. Everytime you start the same service, only the onStartCommand() method is called. Hence if you are using an alarmManager and wants to change a variable in Service you may do it in the onStartCommand(). The onCreate() is called only once when the Service starts for the first time and hence in your case the variable i doesn't change after successive calls to Service.
Check the following for more details:
http://developer.android.com/guide/components/services.html#StartingAService
Related
I want to create an alarm application, which will sound the alarm when you set the time. I've got it to work partially. I'm stuck at the alarm not being set after the app is closed via recent tray(Not with force stop). To tackle this, I created a service which will run in the background(even if the app is closed) and will sound the alarm.
My problem right now, is that even after using a service, I'm unable to sound the alarm after the app is closed. However, the service seems to be running after the closure of the app(I've seen in running apps. It says My App has a service running in the background).
NOTE : I've also bound the service with my activity so that I can use its methods.
NOTE 2 : The service sounds the alarm when the application is open, Only fails to do so when the app is closed.
This is my code :
Calling the service from my Activity :
public void startOnClick(View view) {
int aHour = alarmTimePicker.getCurrentHour();
int aMin = alarmTimePicker.getCurrentMinute();
Alarms alarm = new Alarms(aHour, aMin); //I've created an Alarms class Seperately
myService.setAlarm2(alarm); //Setting the alarm via service
Toast.makeText(this, "Alarm SET.", Toast.LENGTH_LONG).show();
}
In MyService : `package com.wars.tap.tapwars;
public class MyService extends Service {
private final IBinder myBinder = new MyBinder();
Alarms alarm = new Alarms();
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
private ServiceCallBacks serviceCallbacks;
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return myBinder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void setCallbacks(ServiceCallBacks callbacks) {
serviceCallbacks = callbacks;
}
public void setAlarm2(final Alarms alarm){
Runnable r = new Runnable() {
#Override
public void run() {
try {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarm.get_hour());
calendar.set(Calendar.MINUTE, alarm.get_min());
AlarmManager AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(MyService.this, AlarmReceiver.class);
i.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
pendingIntent = PendingIntent.getBroadcast(MyService.this, 934, i, PendingIntent.FLAG_UPDATE_CURRENT);
AM.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} catch (Exception e) {
}
}
};
Thread t = new Thread(r);
t.start();
}
}
`
So, the setAlarm2 is the method I'm using in the service to sound the alarm. It's working when the app is open, but fails to work when the app is being closed. As you can see, this is my first post on StackOverflow and I'm also new to android programming. I've been stuck with this for a long time and would appreciate some help. Thank you.
Your alarm could be working, but the notification center is not aware of allowing your app any privileges to highlight the event that is occurring. Check out this link here for details on Notifications.
EDIT
Check out the code below I extracted from a previous project. I left out the necessary parts:
public class MyClass extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onTaskRemoved(Intent rootIntent) {
// Input your code here prior to exit.
stopSelf();
}
}
I have a Bound service which collects locations for 3 minutes every 15 minutes. I start a CountDownTimer once the Service is connected in onServiceConnected of ServiceConnection.
I receive all the Timer callbacks (onFinish) (onTick) perfectly as far the Activity which bindService is visible.
When Device is locked I do not receive any updates from the timer.
MyLocationService
public class MyLocationService extends Service implements MyTimerListener{
private IBinder mBinder = new MyLocationBinder();
public void onCreate() {
locationManager = new MyLocationManager(this);
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyLocationBinder extends Binder
{
public MyLocationService getService()
{
return MyLocationService.this;
}
}
public void startFetchingLocations()
{
if(locationManager != null){
locationManager.startFetchingLocations();
if(publishPeriodCountDownTimer != null) {
publishPeriodCountDownTimer.cancel();
publishPeriodCountDownTimer = null;
}
publishPeriodCountDownTimer = new MyCountTimer(gpsPublishPeriod * 60 * 1000, 1000, MyLocationService.this);
publishPeriodCountDownTimer.start();
}
}
#Override
public void onTimeFinished() {
//Start fetching locations
locationManager.startFetchingLocations(); //Start 3 min CountdownTimer
}
#Override
public void onTick() {
}
public void onAllLocationsRecieved(ArrayList<Location> locations)
{
//Do stuff on Locations
locationManager.stopFetchingGPS(); //Stops 3 min countdownTimer
}
}
MyActivty
public class MyActivity
{
#Override
protected void onStart() {
super.onStart();
btnStop.setVisibility(View.VISIBLE);
MyNoificationManager.cancelAllNotifications();
if (!isLocationServiceBound) {
Intent locServiceIntent = new Intent(this, MyLocationService.class);
bindService(locServiceIntent, locationServiceConnection, Context.BIND_AUTO_CREATE);
}
}
private ServiceConnection locationServiceConnection = new ServiceConnection(){
#Override
public void onServiceDisconnected(ComponentName name) {
isLocationServiceBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyLocationBinder locationBinder = (MyLocationBinder) service;
locationService = locationBinder.getService();
isLocationServiceBound = true;
locationService.startFetchingLocations();
}
};
}
It works as expected when the Activity is visible. The timer doesn't provide any onTick() or onTimeFinished() callbacks when the device is locked.
What could be the problem here ?
The CountDownTimer will not work when the phone goes to sleep mode. This is by design and it's to save battery life.
Alternately you can use android.app.AlarmManager instead to achieve your goal. Following is the sample code how to do that. Set the alaram like below
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyLocationService.class);
intent.putExtra("need_to_fetch_loc", true);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, gpsPublishPeriod * 60 * 1000, alarmIntent);
Add the following method to your MyLocationService class
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(locationManager!= null && intent.getBooleanExtra("need_to_fetch_loc", false))
{
locationManager.startFetchingLocations();
}
return super.onStartCommand(intent, flags, startId);
}
I have service which do something after a certain period of time. It must continue to work after exitting from my app and restart after rebotting device.
I tried to write something like:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
but then the service does not start.
This is my service example:
public class GetTextService extends IntentService {
public static final String TAG = "testing_intent_service";
private static final int LONG_INTERVAL = 1000 * 10; //10 seconds
private static Context mContext;
private static int debug_i = 0;
public GetTextService() {
super(GetTextService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
Log.d(TAG, debug_i + "");
debug_i++;
if (!isNetworkAvailable) return;
//TODO check changes on the site
}
public static void setServiceAlarm(Context context, boolean isOn) {
mContext = context;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, GetTextService.class);
i.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
PendingIntent pi = PendingIntent.getService(context, 1, i, 0);
if (isOn) {
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), LONG_INTERVAL, pi);
} else {
alarmManager.cancel(pi);
pi.cancel();
}
}
}
And here so I run service:
#Override
public void onCreate(Bundle savedInstanceState) {
...
if (PrefsManager.isFirstLaunch()) {//my custom helper class
GetTextService.setServiceAlarm(this, true);
}
}
UPD: I used BroadcastReceiver which starts service every time after boot. As I see, it works clearly.
The Service code here gets some items from an RSS Feed. And then generates a List of the Items. The method getItems() is the one that exposes what has been brought in.
public class RssService extends Service {
ThisBinder mBinder = new ThisBinder();
private List<Item> items;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Hid some code for brevity
Log.i("items", Arrays.deepToString(items.toArray()));
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
List<Item> getItems(){
return items;
}
class ThisBinder extends Binder{
RssService getService() {
return RssService.this;
}
}}
This BroadcastReceiver here starts the service every 15 minutes.
public class RssReciever extends BroadcastReceiver {
Long REPEAT_TIME = 15L * 60L * 1000L;
// Long REPEAT_TIME = 1000L;
RssService rssService;
IBinder binder;
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
Toast.makeText(mContext, "Connected, total Items, " + rssService.getItems().size(), Toast.LENGTH_SHORT).show();
}
}
I need to use the RssService.getItems() method here so that I can generate a notification. So far I haven't been able to do this. I can't seem to find the proper way to get an instance of the service.
How can this be done?
Presently, I am working on app that works like "To Do Task List". I have successfully implemented the NotificationService and SchedularService in my application. Also I am getting the alerts(Notifications) at the time set for the tasks.
Here are my queries as below:
With this code will my alarms will be deleted after reboot ? If yes, how to overcome this.
I have kept the Priority feature for the tasks. But i want the mechanism such that if user selects priority "High" then he should receive notifications thrice, say, before 30 minutes, before 15 minutes and on the time set. How to achieve this ?
I want to set Phone's vibrate feature when Notifications are raised. How to achieve this ?
And i want to know about, what can be done for the deprecated methods and constructor in NotifyService.java. Thesse are deprecated in API level 11: Notification notification = new Notification(icon, text, time); and notification.setLatestEventInfo(this, title, text, contentIntent);. On developer.android.com, they have suggested to Use Notification.Builder instead. So how to make my app compatible with all the API levels.
Here's my snippet code for scheduling alarm:
...
scheduleClient.setAlarmForNotification(c, tmp_task_id);
...
Here's the class ScheduleClient.java:
public class ScheduleClient {
private ScheduleService mBoundService;
private Context mContext;
private boolean mIsBound;
public ScheduleClient(Context context)
{
mContext = context;
}
public void doBindService()
{
mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
public void setAlarmForNotification(Calendar c, int tmp_task_id){
mBoundService.setAlarm(c, tmp_task_id);
}
public void doUnbindService() {
if (mIsBound)
{
mContext.unbindService(mConnection);
mIsBound = false;
}
}
}
Here's the ScheduleService.java:
public class ScheduleService extends Service {
int task_id;
public class ServiceBinder extends Binder {
ScheduleService getService() {
return ScheduleService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new ServiceBinder();
public void setAlarm(Calendar c, int tmp_task_id) {
new AlarmTask(this, c, tmp_task_id).run();
}
}
Here's the AlarmTask.java:
public class AlarmTask implements Runnable{
private final Calendar date;
private final AlarmManager am;
private final Context context;
int task_id;
public AlarmTask(Context context, Calendar date, int tmp_task_id) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.date = date;
task_id = tmp_task_id;
}
#Override
public void run() {
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
intent.putExtra("task_id", task_id);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
}
}
Here's the NotifyService.java:
public class NotifyService extends Service {
public class ServiceBinder extends Binder
{
NotifyService getService()
{
return NotifyService.this;
}
}
int task_id;
private static final int NOTIFICATION = 123;
public static final String INTENT_NOTIFY = "com.todotaskmanager.service.INTENT_NOTIFY";
private NotificationManager mNM;
SQLiteDatabase database;
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String tmp_task_brief = null;
task_id = intent.getIntExtra("task_id", 0);
loadDatabase();
Cursor cursor = database.query("task_info", new String[]{"task_brief"}, "task_id=?", new String[]{task_id+""}, null, null, null);
while(cursor.moveToNext())
{
tmp_task_brief = cursor.getString(0);
}
cursor.close();
if(intent.getBooleanExtra(INTENT_NOTIFY, false))
showNotification(tmp_task_brief);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new ServiceBinder();
private void showNotification(String tmp_task_brief) {
CharSequence title = "To Do Task Notification!!";
int icon = R.drawable.e7ca62cff1c58b6709941e51825e738f;
CharSequence text = tmp_task_brief;
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, text, time);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TaskDetails.class), 0);
notification.setLatestEventInfo(this, title, text, contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNM.notify(NOTIFICATION, notification);
stopSelf();
}
void loadDatabase()
{
database = openOrCreateDatabase("ToDoDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
}
With this code will my alarms will be deleted after reboot ? If yes, how to overcome this.
Yes alarm will get deleted, to overcome this, you need to use Android's Component called BroadcastReceiver as follows,
First, you need the permission in your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Also, in your manifest, define your service and listen for the boot-completed action:
<receiver
android:name=".receiver.StartMyServiceAtBootReceiver"
android:enabled="true"
android:exported="true"
android:label="StartMyServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Then you need to define the receiver that will get the BOOT_COMPLETED action and start your service.
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("com.myapp.NotifyService");
context.startService(serviceIntent);
}
}
}
And now your service should be running when the phone starts up.
2 For Vibration
Again you need to define a permission in AndroidManifest.xml file as follows,
<uses-permission android:name="android.permission.VIBRATE"/>
Here is the code for vibration,
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 300 milliseconds
v.vibrate(300);