Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7737471
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T08:00:27+00:00 2026-06-01T08:00:27+00:00

I’m new to Java and this is my first post on here so hopefully

  • 0

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!!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T08:00:30+00:00Added an answer on June 1, 2026 at 8:00 am

    you try this one code

    public class Add_todo_list extends Activity {
        protected static final int DATE_DIALOG_ID = 0;
        private static final int TIME_DIALOG_ID = 1;
        private int mYear;
        private int mMonth;
        private int mDay;
        private int mHour;
        private int mMinute;
        private int aY;
        private int aMo;
        private int aD;
        private int aH;
        private int aMi;
    
    
        protected void onResume() {
            // TODO Auto-generated method stub
            getRecords();
            super.onResume();
        }
    
        Button save, clear, back, cat_add;
        EditText title, disc, due_date, alarm_time;
        Spinner category;
        ToggleButton alarm_set;
        RadioGroup priority;
        RadioButton r1, r2, r3;
        private Database_creat mDbHelper;
        private Alarm_set alarmset;
        ArrayAdapter<String> adapter;
    
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.todo_add);
    
            save = (Button) findViewById(R.id.todo_add_Bnt_Save);
            clear = (Button) findViewById(R.id.todo_add_Bnt_clear);
            back = (Button) findViewById(R.id.todo_add_Bnt_back);
            cat_add = (Button) findViewById(R.id.todo_add_Bnt_category_add);
    
            title = (EditText) findViewById(R.id.todo_add_edt_title);
            disc = (EditText) findViewById(R.id.todo_add_edt_description);
            due_date = (EditText) findViewById(R.id.todo_add_edt_due_date);
            alarm_time = (EditText) findViewById(R.id.todo_add_edt_alaram_time);
            category = (Spinner) findViewById(R.id.todo_add_spin_category);
            alarm_set = (ToggleButton) findViewById(R.id.todo_add_togbnt);
            priority = (RadioGroup) findViewById(R.id.todo_add_RadGro_priority);
            r1 = (RadioButton) findViewById(R.id.todo_add_Red_hige);
            r2 = (RadioButton) findViewById(R.id.todo_add_Rad_medium);
            r3 = (RadioButton) findViewById(R.id.todo_add_Rad_low);
    
            mDbHelper = new Database_creat(Add_todo_list.this);
            mDbHelper.Open();
            alarmset = new Alarm_set();
    
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.select_dialog_item);
            getRecords();
            category.setAdapter(adapter);
            category.setPrompt("Category");
    
            //Date editText box display date dialog box 
            due_date.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
            });
            //Time editText box display Time dialog box 
            alarm_time.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(TIME_DIALOG_ID);
                }
            });
            final Calendar c = Calendar.getInstance();
    
    
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            aD = mDay;
            aY = mYear;
            aMo = mMonth;
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);
            updateDisplay();
    
            // Add new Category 
            cat_add.setOnClickListener(new OnClickListener() {
    
    
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(Add_todo_list.this,
                            Add_new_category.class);
                    startActivity(intent);
                }
            });
    
            //Bace button go to Main Activity 
            back.setOnClickListener(new OnClickListener() {
    
                        public void onClick(View v) {
                    // TODO Auto-generated method stub
                    finish();
                }
            });
            clear.setOnClickListener(new OnClickListener() {
    
                            public void onClick(View v) {
                    // TODO Auto-generated method stub
                    title.setText("");
                    disc.setText("");
                    updateDisplay();
                }
            });
    
            // Save Button to DataBase in Save info
            save.setOnClickListener(new OnClickListener() {
    
                        public void onClick(View v) {
                    // TODO Auto-generated method stub
    
    
                    String a = title.getText().toString().trim();
                    String b = disc.getText().toString().trim();
                    String c = due_date.getText().toString().trim();
                    String d = alarm_time.getText().toString().trim();
                    String e = category.getSelectedItem().toString();
                    String f = alarm_set.getText().toString();
                    String g = getradio(priority.getCheckedRadioButtonId());
                    String currentDateTimeString = DateFormat.getDateInstance()
                            .format(new Date());
                    // Log.v("save", g+" ");
                    Intent intent;
                    if (a.length() != 0 && b.length() != 0 && mYear >= aY && mMonth >= aMo && mDay >= aD) {
                        // if(c currentDateTimeString){
                        mDbHelper.insert_todoinfo(a, b, c, d, e, f, g);
                        Toast.makeText(Add_todo_list.this, "Add New Note ",
                                Toast.LENGTH_SHORT).show();
    
                         finish();
    
                        // DateFormat formatter;
                        // Date date = null;
                        // formatter = new SimpleDateFormat("MM-dd-yyyy");
                        // try {
                        // date = (Date) formatter.parse(c);
                        // } catch (ParseException e1) {
                        // // TODO Auto-generated catch block
                        // e1.printStackTrace();
                        // }
    
                         // Alarm Set Save with
                        Cursor cursor = mDbHelper.getId(c, d);
                        int getid = 0;
                        Log.v("cursor", "" + cursor.getCount());
                        while (cursor.moveToNext()) {
                            String id = cursor.getString(0);
                            getid = Integer.parseInt(id);
                        }
                        alarmset = new Alarm_set();
                        alarmset.Alarmset(Add_todo_list.this, c, d, getid);
    
                    } else {
                        Toast.makeText(Add_todo_list.this,
                                "Enter Title,Discription and Velid Date ", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
    
            });
        }
    
        private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                    updateDisplay();    
            }
        };
    
        private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplay();
            }
        };
    
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
                        mDay);
    
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this, mTimeSetListener, 0, 0, false);
    
            }
            return null;
        }
    
        private void updateDisplay() {
            // TODO Auto-generated method stub
            due_date.setText("");
            alarm_time.setText("");
            due_date.setText(new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-").append(mDay).append("-")
                    .append(mYear));
            alarm_time.setText(new StringBuilder().append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    
    
    
        }
    
        private Object pad(int x) {
            // TODO Auto-generated method stub
            if (x >= 10)
                return String.valueOf(x);
            else
                return "0" + String.valueOf(x);
    
        }
    
        //Get List of Category
        private void getRecords() {
            // arrayList.clear();
            adapter.clear();
            Cursor cursor = mDbHelper.getInfoRecords();
    
            while (cursor.moveToNext()) {
                String id = cursor.getString(0);
                String Categore = cursor.getString(1);
                adapter.add(Categore);
            }
        }
    
        //RedioButton Select to get Radio String 
        private String getradio(int id) {
            // TODO Auto-generated method stub
    
            String ab = null;
            switch (id) {
            case R.id.todo_add_Rad_low:
                ab = r3.getText().toString();
                break;
            case R.id.todo_add_Rad_medium:
                ab = r2.getText().toString();
                break;
            case R.id.todo_add_Red_hige:
                ab = r1.getText().toString();
                break;
            }
            return ab;
        }
    }
    

    and other one class

    public class Alarm_set extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
        }
       //Set Alarm 
        public void Alarmset(Context cont, String c, String d, int getid) {
            Log.v("alaramiuughuhuiohioh", "dfdd");
    
            int cd = 0, cy = 0, cmo = 0, ch = 0, cmi = 0, cm = 0;
            String date = c.substring(3, 5);
            String month = c.substring(0, 2);
            String Year = c.substring(6, 10);
            String min = d.substring(3, 5);
            String hours = d.substring(0, 2);
            Log.v("get ste", date + "-" + month + "-" + Year);
    
            cd = Integer.parseInt(date);
            cy = Integer.parseInt(Year);
            cm = Integer.parseInt(month);
            cmo = cm - 1;
            ch = Integer.parseInt(hours);
            cmi = Integer.parseInt(min);
            Calendar cal = Calendar.getInstance();
            cal.set(cy, cmo, cd, ch, cmi);
            Log.v("set", cy + "-" + cd + "-" + cmo + "-" + ch + "-" + cmi);
            Log.v("alarm set", "alarm set in " + cal.getTimeInMillis());
    
            Intent intent = new Intent(cont, AlarmReceiverActivity.class);
            intent.putExtra("id",getid);
            PendingIntent penintent = PendingIntent.getBroadcast(cont, getid,
                    intent, 0);
            AlarmManager alm = (AlarmManager) cont.getSystemService(ALARM_SERVICE);
            alm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), penintent);
    
        }
    
        //Delete Alarm 
        public void Alarmcancel(Context cont, int id) {
            Intent intent = new Intent(cont, AlarmReceiverActivity.class);
            PendingIntent penintent = PendingIntent.getBroadcast(cont, id, intent,
                    0);
            penintent.cancel();
            //Toast.makeText(cont, "alarm stop", Toast.LENGTH_LONG).show();
        }
    
    }
    

    and broadcast class

    public class AlarmReceiverActivity extends BroadcastReceiver {
        private static final int MODE_WORLD_READABLE = 0;
        private NotificationManager nm;
        private Database_creat mDbHelper;
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String descr = null;
            mDbHelper = new Database_creat(context);
            mDbHelper.Open();
            int id = intent.getIntExtra("id",0);
            Log.v("alarmreciev Id ",id+"");
            String sub_id = String.valueOf(id);
            String alarm_set = null;
            String title = null ;
            SharedPreferences myPrefs;
    
            // Get Title,Description And Set Status Bar Notifications
            Cursor cursor = mDbHelper.getdata_disp(id);
            while (cursor.moveToNext()) {
                String Title = cursor.getString(0);
                String Description = cursor.getString(cursor.getColumnIndex("description"));
                 alarm_set =cursor.getString(cursor.getColumnIndex("alarm_set"));
                 title = cursor.getString(cursor.getColumnIndex("title"));
    
                descr = Description;
            }
    
             nm = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
    
                  CharSequence from = "To Do List";
                  Intent disintent = new Intent(context,Todo_display_win.class);
    
                  disintent.putExtra("id",sub_id);
                  Log.v("send to display Id", sub_id);
                  CharSequence message = title;
                  Notification notif = new Notification(R.drawable.notes,
                            "To do List", System.currentTimeMillis());
                  notif.flags=Notification.FLAG_AUTO_CANCEL;
    
                  PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                          disintent,Notification.FLAG_AUTO_CANCEL);
    
                  notif.setLatestEventInfo(context, from, message, contentIntent);
                  nm.notify(1, notif);
                  //nm.cancel(1);
                  //notif.defaults |= Notification.FLAG_AUTO_CANCEL;
    
    
    
    
                  if(alarm_set.equals("on"))
                  {
                      Toast.makeText(context,title, Toast.LENGTH_LONG).show();
                  }
    
                  myPrefs = context.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
                  String on = "on";
                    Log.v("sound", myPrefs.getString("sound", "off"));
                    if (on.equals(myPrefs.getString("sound", "off"))) {
                        notif.defaults |= Notification.DEFAULT_SOUND;
                    }
                    Log.v("vibrate", myPrefs.getString("vibrate", "off"));
                    if (on.equals(myPrefs.getString("vibrate", "off"))) {
                        notif.defaults |=Notification.DEFAULT_VIBRATE;
                    } 
                    Log.v("light", myPrefs.getString("light", "off"));
                    if (on.equals(myPrefs.getString("light", "off"))) {
                        notif.defaults |= Notification.DEFAULT_LIGHTS;
                    } 
        }
    
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to create an if statement in PHP that prevents a single post
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.