Search code examples
androidbroadcastreceiveralarmmanagerandroid-workmanagerandroid-jobscheduler

open phone dialer even if app is closed on specific time


I want to open android phone dialer on specific time from my app even if my app is closed.

I tried AlarmManager for this -

                AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                Intent intent = new Intent(this, CallSchaduleBroadcast.class);
                intent.putExtra("PHONE_NUMBER", edtPhone.getText().toString());
                PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC, timeInMillis, pendingIntent);

and this is my onReceive method in CallSchaduleBroadcast class-

            String number = intent.getStringExtra("PHONE_NUMBER");
            Intent callIntent = new Intent(Intent.ACTION_DIAL);
            callIntent.setData(Uri.parse("tel:" + number));
            context.startActivity(callIntent);

but this gives me following error-

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I am building my app with-

    minSdkVersion 21
    targetSdkVersion 29

Is this correct way to get my work done or I need to try something else like Job Scheduler or Work Manager. Please help me, Thanks in advance


Solution

  • My bad, I got the solution

                    String number = intent.getStringExtra("PHONE_NUMBER");
                    Intent callIntent = new Intent(Intent.ACTION_DIAL);
                    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    callIntent.setData(Uri.parse("tel:" + number));
                    context.startActivity(callIntent);
    

    I just have to setFlags to FLAG_ACTIVITY_NEW_TASK in callIntent.

    But still I want to know if there is any better solution using Job Scheduler or Work Manager. Thanks