I am currently experimenting with Android I was wondering how i can make postDelayed run after I hit the home button?
Using handler I am able to make the postDelayed run every minute so that a integer is increased by one, but I want the integer to keep increasing even after I leave the app by pressing the home button.
Is there solution to my problem?
You can use AlarmManeger to start your Service in a specific time. Here is an example with NotificationService:
Log.i(TAG, "Setting intent");
Intent intent = new Intent(context, NotificationService.class);
Log.i(TAG, "Setting pendingIntent");
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Log.i(TAG, "Setting alarm");
alarmManager.set(AlarmManager.RTC_WAKEUP, time.getMillis(), pendingIntent);
Related
I am trying to poll a device for long/lat every minute or so... I have been researching and found a few things. I was thinking of using:
PeriodicWorkRequestBuilder() - however, I have read that it can only execute every 15 minutes at a minimum...
What tech/design pattern are available to me, if I wanted to poll for data in a shorter period?
Are foreground services my only choice?
You can Use any Runnable but when app closed it will not working .
Foreground service is best choice but in android 9+, it will confuse the user
this is the link that show to you how use it:
Timer
BUT
I advice you to use an AlarmManager that work like work manager but it response better, you can Use Countdown timer for it, link below will help You to use it:
AlarmManager
Edited:
sample for open activity with alarm manager
Intent intent = new Intent(this, YOUR_MAIN_ACTIVITY.class);
intent.setAction(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, ID,
intent, 0);
final long DELAY_IN_MILLIS = DELAY_IN_MILLI_SECONDS+
System.currentTimeMillis();
AlarmManager alarmManager = (AlarmManager)
getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, DELAY_IN_MILLIS,pendingIntent);
and there is a full example for you:
Example
The main part of my app is a service that displays a notification. The GUI of the app is only used to be able to change some settings. When I click on that notification, some data should be send in the background without opening the app. To do that, I created an invisible activity.
When I open the app (the configuration part) and exit it with the back button, everything works as intended; when clicking on the notification the data is send without opening the app.
When I exit the app with the home button, every time I click the notification the app opens again.
This is my notification and the Intent to call the data activity:
PendingIntent toggleLightsIntent =
PendingIntent.getActivity(
this,
0,
new Intent(this, HyperionToggleSwitchActivity.class),
PendingIntent.FLAG_NO_CREATE);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("HyperionSwitch")
.setContentText("Switch lights")
.setContentIntent(toggleLightsIntent)
.build();
And this is the part where I send the data:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendJson(blue);
finish();
}
What do I have to change so the app won't open when clicking the notification?
It's my first app and took me quite a while to get what I have so far...
As per earlier comment:
You could change your hidden activity into a Service (which generally doesn't have any ui), or leverage the service that manages the notification, and have the PendingIntent sent directly to that service using PendingIntent.getService() .
Try this code^
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.FILE_NAME, "somefile");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
I need that my application restarts when click a button, for more info I need simulate thant I push back key and open application again.
I supose that i can close application with finish(); but how can i do to launch onCrete() again?
is there other way to do this?
thanks
Call your Activity using an Intent. It will launch the activity again.
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this will always start your activity as a new task
startActivity(intent);
You can also add, android:launchMode="singleTask" inside your Manifest so that only one instance of your activity will be maintained at any time.
Same thing here. :)
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
To restart your application you can use alarm manager to make your activity open after you exit the app.
AlarmManager alm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alm.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0));
android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
I want to program an app that has two independent, repetitive alarms. There are two classes seem to be able do this: AlarmManager and AlarmClock. I've tested AlarmManager, but when Android restarts all alarms are cleared.
Which should I use?
Use BroadcastReceiver to handle Android OS boot broadcast and reschedule your alarms.
AlarmManager services allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running.
You may find the SO post helpful Android AlarmManager
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
Whereas AlarmClock provider contains an Intent action and extras that can be used to start an Activity to set a new alarm in an alarm clock application.
I have a GPS service whose work is to fetch the coordinate into a server. This service suppose to be run 24/7. but it is somehow killed in between.
This is happing only in android v 2.3. On android v2.2 it's running fine.
In this service , i am using "LocationManager" and it's method "requestLocationUpdates" which is creating a loop.This loop is responsible for fetching the coordinates. So my goal is to keep the loop running.
So what to do, to make by service run 24/7.
This server suppose to be run 24/7
You cannot do that. This is not possible in any real sense of the term, as you have discovered. It is also not a good design choice at all.
If you absolutely need it to be running all the time, you need to
acquire a PARTIAL_WAKE_LOCK via PowerManager. This will keep the CPU
on all the time, and your program running. Be prepared for a shocking
decline in battery life.
Instead use AlarmManager. You can schedule a PendingIntent via the AlarmManager thats starts the service at the relevant point in time to do it's work. When done, kill the service again.
Below is a sample code showing how the AlarmManager is used which will launch the intent to start YourService in 5 minutes from now:
// get a calendar with the current time
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 5);
Intent intent = new Intent(ctx, YourService.class);
PendingIntent pi = PendingIntent.getService(this, 123, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
Please use repeating Alarm Manager which start your service after a given time period
private void setAlarm() {
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
intent.putExtra("locationSendingAlarm", true);
PendingIntent pendingIntent = PendingIntent.getService(this, AppConstants.PENDING_INTENET_LOCATION_SENDING_ALARM_ID, intent,0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
}
int timeForAlarm=5*1000*60; // 5 minutes
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+timeForAlarm, timeForAlarm,pendingIntent);
}