2

I want to repeat a function( or any action ) every one Hour ( for example ) even if the app is not running.

WIKOSO
  • 105
  • 1
  • 2
  • 12
  • 1
    A question of this type should also include attempts to resolve the problem by oneself and why that attempt did not work. See https://stackoverflow.com/help/how-to-ask – EpicPandaForce Mar 26 '19 at 18:09
  • i tied many codes and no of them has work, why i will put a wrong code i want just a new way a new idea – WIKOSO Mar 26 '19 at 18:15
  • what you are saying is "I do not understand what the code I try to use do". So maybe you should go back step or two and step up your basics? – Marcin Orlowski Mar 26 '19 at 18:58
  • Yes, i should do that but i'm not talking about loops brother !! – WIKOSO Mar 27 '19 at 19:38

2 Answers2

2

I've created a demo project so you can take a look at it :

https://github.com/joancolmenerodev/BroadcastReceiverAndAlarmManagerInKotlin


You first have to create a BroadcastReceiver, and then using AlarmManager you can decide the interval of time you want to be called.

Create a BroadcastReceiver you can do it as follows :

val broadCastReceiver = object : BroadcastReceiver() {
     override fun onReceive(contxt: Context?, intent: Intent?) {
         toast("This toast will be shown every X minutes")
     }
}

And then you have this method to start the job :

val mIntent = Intent(context, broadCastReceiver)

val mPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, mIntent, 0)
val mAlarmManager = context
    .getSystemService(Context.ALARM_SERVICE) as AlarmManager
mAlarmManager.setRepeating(
    AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(),
    CHANGETOYOURDESIREDSECONDS, mPendingIntent
)

And then you'll be able to see the Toast even if the app is closed.

Edit

You can register your BroadcastReceiver using context.registerReceiver(receiver, IntentFilter("something")) and then adding to the mIntent and action for "something".

If you don't like this way, you can create a new class named MyReceiver that extends BradcastReceiver as follows :

class MyReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        Toast.makeText(context,"This toast will be shown every X minutes", Toast.LENGTH_SHORT).show()
    }
}

And then start the alarm doing this :

val mIntent = Intent(this, MyReceiver::class.java)

val mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        val mAlarmManager = this
            .getSystemService(Context.ALARM_SERVICE) as AlarmManager
        mAlarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            WHATEVERYOUWANT, mPendingIntent
        )

Note: By default is set to 60000

Value will be forced up to 60000 as of Android 5.1; don't rely on this to be exact

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • there is a problem in this line : val mIntent = Intent(context, broadCastReceiver) i use val mIntent = Intent(this, broadCastReceiver) but still the same problem – WIKOSO Mar 26 '19 at 18:23
  • Please, check my repository, you have to add the receiver to manifest.xml – Skizo-ozᴉʞS ツ Mar 26 '19 at 18:55
  • That's another quesiton @WIKOSO, and no, it does not, you have to code a little bit to produce this issue, if you want create a different quesiton explainin what you've tried and what you want to achieve and I can take a look – Skizo-ozᴉʞS ツ Mar 26 '19 at 19:16
  • this method works fine in the Emulator but it is not working in real devices, what's wrong? – WIKOSO Mar 27 '19 at 10:53
  • there is not an error just the Toast it does not run when i use a real device – WIKOSO Mar 27 '19 at 11:41
1

If you are using AndroidX(JetPack) library then concider to use Workmanager

Simple example:

public class MyWorker extends Worker {

    static final String TAG = "workmng";

    @NonNull
    @Override
    public WorkerResult doWork() {
        Log.d(TAG, "doWork: start");

       //Do your job here

        Log.d(TAG, "doWork: end");

       return WorkerResult.SUCCESS;
    }
}

And start like this, to do your job each hour :

PeriodicWorkRequest myWorkRequest = new PeriodicWorkRequest.Builder(MyWorker.class, 60, TimeUnit.MINUTES)
   .build();

Add in app gradle file:

dependencies {
def work_version = 2.0.0

// (Java only)
implementation "androidx.work:work-runtime:$work_version"
}
Jurij Pitulja
  • 5,546
  • 4
  • 19
  • 25