I’m new to Java and this is my first post on here so hopefully someone can help me. I’ve checked every website that came up in google to find the answer to this with no luck. So I am trying to set up a repeating alarm that generates a random number every 24 hours from the set time. I am using alarm manager and can only seem to find code examples of using alarm manager to start activities or services. What I want to do is use alarm manager to run a simple command thats already inside of an activity. (If theres another way to do this please let me know)
Here is an example of what I have and what im trying to accomplish
import java.util.Calendar;
import java.util.Random;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class ExampleCode extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); // Here I want to set an alarm
Calendar twentyFourHourCalendar = Calendar.getInstance();
twentyFourHourCalendar.set(Calendar.HOUR_OF_DAY, 24); // At midnight
twentyFourHourCalendar.set(Calendar.MINUTE, 0);
twentyFourHourCalendar.set(Calendar.SECOND, 0);
Intent someIntent = new Intent("com.example.SomeOtherProcess"); // Instead of an activity I want it to run the generateRandom() method below
someIntent.putExtra("NotifID", 1);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0, someIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
twentyFourHourCalendar.getTimeInMillis(), displayIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, twentyFourHourCalendar // I want it to generate a random number every midnight without any user interaction
.getTimeInMillis(), 24 * 60 * 60 * 1000, displayIntent);
}
public void generateRandom() // This is the method that I want to repeat
{
Random generator = new Random();
int randomNumber = generator.nextInt(2);
}
}
All I want to do is call the generateNumber() method every twenty four hours I’m sure the solution is very simple I think Ive been looking at the code too long to figure it out lol. Any help will be greatly appreciated!!!
you try this one code
and other one class
and broadcast class