How to periodically run a task? - java

I started building my app to send JSON strings to a server, however it is only sent when I click a button. I would like it to be sent automatically after a time that is specified by the user from a TimeDialog. I was suggested to use AlarmManager or Handler, but I do not know how to implement it with my app. I have provided the line of code that will be executes and sends to my server. Any help or suggestions?
Code used I would like it to be run after specified time:
public void onClick(View view) {
switch (view.getId()) {
case R.id.saveBtn:
if (!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().onPostExecute("server_adress"); //was execute but changed!
break;
}
}

You can use Java Util Timer class to do what you want.
you can see here an example.
Try to use it!!!

While an alarm manager/handler is often the best way schedule future events on Android, Google suggests using a Sync Adapter when scheduling network calls like your application synching to the server at a given interval. The framework provides a predefined user authentication, background scheduling so that you app does not need to be running to make the call, improved battery performance, and handling the case when there is no network connectivity at the time scheduled. Here's their developer page on using Synch Adapters.

Related

How to trigger KeygaurdManager to take fingerprint programmatically

As soon as I receive a push notification from my app I want to trigger the KeyguardManager to launch the fingerprint/pass code screen to open the phone from lock screen so that person can enter the phone and unlock the device.
I want to trigger this programmatically similar to when we click on any notification from lock screen we get the fingerprint/pass-code screen.
I did a lot of RnD but didn't find any solution, this is one of the challenging use case task given to me in class, I have been exploring a lot from quite few weeks with no success at all.
Did tried Broadcast receiver with BiometricManager and many things with no success, any lead will be very helpful.
As soon as you receive push message, onNotificationReceived() (or some other method if you use some 3rd party libs) method gets called as below. from there, you can launch your Main screen where you have written biometric/unlocking code.
class MyReceiver : PushReceiver {
override fun onNotificationReceived(message: Message) : Boolean {
//Launch your MainActivity where you can show Unlock screen.
return super.onNotificationReceived(message);
}
}

Making API calls while app is killed/not actively running

So I am making an app that has to check for some information, but I need to be able to do that while the app is killed/not actively running. So basically like Youtube's notifications or something. I am a beginner and watched some tutorials on FCM, which can send a notification while the app is killed, which is fine. However, I need to be able to periodically make API calls, check if a certain condition is true and send the notification if so (all of that while app is not running). I tried googling that and found nothing that can help me. So... any ideas? (No code included since I don't think it's relevant.)
If this condition only affects the display of notifications, you can simply check the condition when you receive a notification through FCM. Here's an example :
class FCMService : FirebaseMessagingService()
{
override fun onMessageReceived(message: RemoteMessage)
{
val myCondition = getConditionFromAPI()
if (myCondition) {
showNotification(message)
}
}
}
Use AlarmManager to request periodic runs of your code. It may be set up to broadcast a message time to time to your receiver (declared in AndroidManifest.xml or in your code).
It will work while device is on. To continue after reboot, you have to set up a receiver for Intent.ACTION_BOOT_COMPLETED and register it in your code (not in AndroidManifest.xml, as it no longer works in latest versions of Android).

how to keep alive activity with notification and runnable every second

I have an activity that demonstrates information ping results about servers. This job is done every second with runnable like below code:
pingRunnable = new Runnable() {
#Override
public void run() {
pingMethod();
resultsNotification();
handler.postDelayed(this, 1000);
}
};
on the other hand, I have to show some results in the notification realtime and I did it, But there is a problem, that in the first when the device was locked after 10 min app and activity was destroyed by OS and just notification stopped in a stagnant status. then I tried to fix it with below code:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
wl.release();
Actually, I used wl.release(); like this:
#Override
protected void onDestroy() {
wl.release();
super.onDestroy();
}
It got better when I did it, but when the device was locked this again happened after some hours.
Right now I don't know exactly how can I control these services (background(Runnable) and foreground(Notification) ) together for keeping alive activity for a long time such as two or three days or even more.
First up you shouldn't be using an Activity to do this kind of work a Service is the recommended approach. To do this kind of work intelligently you have a number of options with the Android framework, most recently the new WorkManager component. These services should offer you the ability to control when your background work is scheduled - e.g. only running when a valid network connection is present and by allowing you to select a period when the work should run.
https://developer.android.com/topic/libraries/architecture/workmanager/advanced
Secondly, polling every second will have a drastic impact on battery life - if you do this most likely your app will be flagged as a bad citizen and be a likely candidate for uninstalling.
You should consider whether polling in general is the best option for your users. Using cloud messaging would improve the amount of work your app needs to do to, i.e. you could just push out a notification when the server data changes, which avoids you having to do the manual polling. https://firebase.google.com/docs/cloud-messaging/

How can I get my android app to execute code when a notification is received when it's in background?

I'm trying to program a remote alarm clock application for Android, because my friend sometimes misses her train or is too early (I don't want to wake up, but just want her to set my alarm clock time).
I figured out how to set the alarm clock using Java in just a couple of minutes, but that function must be executed remotely. How to do that?
At the moment I'm using Googles Firebase Cloud Messaging service to send notifications including the time for the alarm clock as parameters.
However, when I receive them and the app isn't open, it doesn't execute any code, but waits until the user taps on the notification. But what I want the app to do is set the alarm clock automatically when a notification is received.
I know this does probably violate a bunch of security guidelines, but this isn't an app for the PlayStore, but just for myself.
My idea is to built some kind of service that's active all the time in the background waiting for notifications. Do you think something like that is possible?
Thanks for your help :-)
Try to pass notification payload to the service class and there you can set alarm manager in the background.
We cannot get notification information when app killed or at background, but if notification arrived, the onCreate of FirebaseMessagingService will be fired, so we could try to get notification information from your backend server in onCreate.
public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "in onCreate, try to get informations from backend server, ex..send http request here");
}

Starting an update checker thread, checking for new entries in a database

I need some suggestions for approaches to take...
Here's some background info:
Right now I have an Android app and a separate java program running on my server.
The java program continuously go out and gets information from different sites and stores them in 14 different entries in an SQL database on the server.
The Android app then queries the databases to retrieve the info to be displayed.
My goal:
I need suggestions on how to have the app handle checking for updates from the database, and then letting the user know that there is new information.
My first thought is that maybe I need to start a separate thread that queries the database for a time modified. Then if it finds updates, it would pop up on the screen that there is new information.
I'm not too well educated with the way threads or services work, so I guess I'm looking for how to implement this, or whether there is a completely different way to go about update checking that would be better.
Thanks in advance, I appreciate any feedback, input, or suggestions.
Hi Ryan I have also implemented a similar thing in my android app and surprisingly I also had 14 tables in my PostgreSQL Server. First of all, you would want to poll the server periodically even when the app is not in the foreground. For that you need to run a background Service - here you will have to manually create a thread in the service, because Service by default runs on the UI thread OR use an IntentService - you don't have to create a separate thread. Whatever code you write in the intent service will be handled in a different thread automatically
Now you have to make this service execute periodically. For that use an AlarmManager and use the setRepeating()function. In the arguments you have to give a PendingIntent to your Service or IntentService. But don't use an alarm manager if you are going to poll the server for every less than 1 minute. Because the battery will be wasted a lot.
Here is some code that might give you an idea :
function setalarm()
{
Intent intent = new Intent(getBaseContext(), Intent_Service.class);
PendingIntent sender = PendingIntent.getBroadcast(getBaseContext(), 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Random randomGenerator = new Random();
long interval=60000; //1 minute in milliseconds
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(),interval,sender);
}
This is Intent_Service of type IntentService :
public class BackService extends IntentService
{
Context context=this;
//public Timer t=null;
public BackService()
{
super("myintentservice");
}
#Override
protected void onHandleIntent(Intent intent)
{
try
{
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
//..CPU will remain on during this section..
//make our network connections, poll the server and retrive updates
//Provide a notification if you want
wl.release();//Release the powerlock
}
}
}
But if you want instantaneous updates, then use Google Cloud Messaging Services. To know more about how it works see this
Hope this helps you.

Categories

Resources