Alarm During Specific time Android Application - java

Can anyone inform me how can I create an alarm in android application that starts from current time and it'll be repeated for each 10 minutes during specific time?
For example, depending on different cases the time that the alarm should repeate is during 2 hours, another case it might be just 1:30 hour and so on.
Is there any way to do that?
Actually I used a code I took it from the web, as shown below:
public class MyAlarmService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG)
.show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG)
.show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "...", Toast.LENGTH_LONG)
.show();
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG)
.show();
return super.onUnbind(intent);
}
}

You can use a BroadcastReceiver and an PendingIntent. First you declare an BroadcastReceiver:
public class EventAlarmReceiver extends BroadcastReceiver {
private long alarmTime;
#Override
public void onReceive(Context context, Intent intent1) {
//declare the new time for the alarm, you can use a time stamp, for example in the next hour
alarmTime = Calendar.getInstance().getTimeInMillis()+(60*60000);
//set an intent to the Receiver
Intent intent = new Intent(context, EventAlarmReceiver.class);
//set an PendingIntent to the Intent
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 234324243, intent, 0);
//add to the System Alarm Manager
AlarmManager alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, alarmTime, pendingIntent);
}
}
and start the alarm in the Activity:
Intent intent = new Intent(context, EventAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, time, pendingIntent);

Related

Repeating actions using Alarm in Android background service

I wrote this code in MainService.java that is called in foreground by using startForeground method. I want to make a toast message in every 10 seconds but it doesn't work. How can I fix it??
public void Alarm(){
Intent intent = new Intent("AlarmService");
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime() + 10 * 1000;
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, sender) ;
} else {
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, sender);
}
} else {
am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, sender);
}
}
BroadcastReceiver alarmReceiver;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
alarmReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub\
count++;
Toast.makeText(getApplicationContext(),count+"times",Toast.LENGTH_LONG);
Alarm();
}
};
registerReceiver(alarmReceiver, new IntentFilter("AlarmService"));
}
Take a look at https://developer.android.com/topic/libraries/architecture/workmanager to do Background tasks

Android How to keep Running the background service when app is killed by user?

I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000,
pendingIntent);
}
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("myFCMJob")
.build();
dispatcher.mustSchedule(myJob);
}
else
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
}}
I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
//setReceiver();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 0);
alarmStartTime.set(Calendar.SECOND, 5);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
//alarmStartTime.add(Calendar.DATE, 1);
}
if (alarmManager != null) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
alarmStartTime.getTimeInMillis(),
pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}
Thanks in Advance.
To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification.
It is also convenient to acquire a partial WAKE LOCK.
on your onStartCommand()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
.setContentTitle("the content title")
.setContentText("the content text")
.setSmallIcon(R.drawable.myicon)
.setOngoing(true);
// you can add other options Builder has
startForeground(1234, mBuilder.build());

after cancelling alarm manager, setting it again doesn't work(no notification)

I'm trying to make my app issue a notification at a specific time(using timePicker) and repeat it daily(using setRepeat method).
Everything is working fine until I cancel the alarm to check if cancellation works or not. But after canceling the alarm if I set the alarm again to issue a notification, it just doesn't work unless my app is running.
I've turned an activity into a dialog and starting with startActivityForResult, getting time setting on the calendar which alarm manager uses. Thanks in advance.
NotificationCenter.class (java file of the activity cum dialog):
// IMPLEMENTATION OF TIME PICKER'S TIME CHANGE EVENT
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
savedHour = hourOfDay;
savedMinute = minute;
}
});
// IMPLEMENTATION OF SAVE BUTTON
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//using this for couple of reasones
Boolean isNotification = notificationSwitch.isChecked();
editor.putBoolean("isNotification", isNotification);
editor.putInt("saved_hour", savedHour);
editor.putInt("saved_minute", savedMinute);
editor.putBoolean("hasTimeSaved", true);
editor.apply();
//sending this intent to mainActivity as a result
Intent result = new Intent();
result.putExtra("saved_hour", savedHour);
result.putExtra("saved_minute", savedMinute);
setResult(2, result);
finish();
}
});
MainActivity.xml
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To remove status bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
// ALARM SERVICE FOR NOTIFICATION
alarmService = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar = Calendar.getInstance();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
alertIntent = new Intent(this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// GET THE NOTIFICATION LINEAR LAYOUT AND SET AN ON CLICK LISTENER TO IT
LinearLayout notificationManager = (LinearLayout) findViewById(R.id.notification_manager);
notificationManager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(getApplicationContext(), NotificationCenter.class), 11);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 11) {
Toast.makeText(this,"request_code_ok", Toast.LENGTH_SHORT).show();
if (resultCode == 2) {
Toast.makeText(this,"result_code_ok", Toast.LENGTH_SHORT).show();
if (preferences.getBoolean("isNotification", false)) {
Toast.makeText(this, "true", Toast.LENGTH_SHORT).show();
int savedHour = data.getIntExtra("saved_hour", 0);
int savedMinute = data.getIntExtra("saved_minute", 0);
calendar.set(Calendar.HOUR_OF_DAY, savedHour);
calendar.set(Calendar.MINUTE, savedMinute);
calendar.set(Calendar.SECOND, 1);
Intent alertIntent = new Intent(this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmService.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
} else {
alarmService.cancel(pendingIntent);
Toast.makeText(this,"alarm_cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}
MyBroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// NOTIFICATION
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setTicker("Alert!")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, ChapterOne.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ChapterOne.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setPriority(2);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify( 0,mBuilder.build());
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="false"/>
<service android:name=".NotificationService" android:enabled="true" android:exported="false"/>

how to execute three different task with serial time manner?

i need to execute three different task and each task should be execute like 1000ms , 2000ms, 3000ms.
can you tell me better way to implement and which is best of following
1. Handler
2. Timertask
3. Thread
4. ExecutorServices and so on
i am using handler for
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 1000);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 2000);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 3000);
}
You can use AlarmManager to perform the operation:
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
alarmIntent.putExtra("Activity",1);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, pendingIntent);
alarmIntent = new Intent(this, AlarmReceiver.class);
alarmIntent.putExtra("Activity",2);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2000, pendingIntent);
alarmIntent = new Intent(this, AlarmReceiver.class);
alarmIntent.putExtra("Activity",3);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3000, pendingIntent);
AlarmReceiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
int extra = intent.getExtra("Activity");
switch(extra) {
case 1:
//start 1st activity
case 2:
//start 2nd activity
case 3:
//start 3rd activity
}
}
}

Error notification when i close my app

i am doing an application that will notify the user after 2 weeks. but i set the timer in 2 mins so i could test if my application will notify the user. my problem is when i turn on the notification and close my app. i will get an error in 2 minutes no notification but when my app is running the notification is working fine. In the logcat my error is in Bundle showData = i.getExtras(); i think the problem is when i closed my app, the Bundle passData is getting null?
PhoneInformation.java
case R.id.bTurnOn:
Bundle passData = new Bundle();
Intent intent = new Intent(PhoneInformation.this,NotificationService.class);
passData.putInt("keyid", rowId);
intent.putExtras(passData);
startService(intent);
break;
NotificationService.java
public class NotificationService extends Service{
int rowId;
private Timer timer = new Timer();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "OnCreate()", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
}
#Override
#Deprecated
public void onStart(final Intent i, int startId) {
// TODO Auto-generated method stub
super.onStart(i, startId);
final Handler handler = new Handler();
Timer timer;
TimerTask timertask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#SuppressWarnings("deprecation")
public void run() {
Bundle showData = i.getExtras();
rowId = showData.getInt("keyid");
Bundle passData = new Bundle();
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(NotificationService.this,SMSPhoneMessage.class);
passData.putInt("keyid", rowId);
notificationIntent.putExtras(passData);
PendingIntent pendingIntent = PendingIntent.getActivity(NotificationService.this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis());
notification.setLatestEventInfo(NotificationService.this, "New Message", "Please come to me immediately", pendingIntent);
nm.notify(123, notification);
}
});
}
};
timer = new Timer();
timer.schedule(timertask, 10000);
}
}

Categories