Android: status bar notifications in specific time - android

I have app which in specific time start notification in status bar.But when that time elapsed, every time when I launch the app he start the notification again.
Thanks in advance.
Here is the code:
Activity: MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//notifications with solve problem
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 30 );
calendar.set(Calendar.SECOND, 0);
calendar.getTimeInMillis();
long current_time = System.currentTimeMillis();
long limit_time = calendar.getTimeInMillis();
if (current_time > limit_time) {
//nothing
} else {
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
}
}
Activity: MyReceiver
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
Activity: MyAlarmService
public class MyAlarmService extends Service{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"Run this app", System.currentTimeMillis() );
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "Horoscope", "Run this app", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
I solve the problem with this post - Notification at specific time

use
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), SYNC_REPEAT_MILLSECONDS, pendingIntent);
instead of
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

Related

how to show notification when app is not running

My Scenario is to show Greeting notification to my users even they are not using the app. Below code is working fine if the open is opened or minimized. But, I want to show the notification in morning even though the user did not open the application.
Main Activity:
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} //end onCreate
}
My Receiver Class:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
/*Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);*/
try{
Utils.generateNotification(context);
}catch(Exception e){
e.printStackTrace();
}
}
}
Utils Class:
public class Utils {
public static NotificationManager mManager;
#SuppressWarnings("static-access")
public static void generateNotification(Context context){
mManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent intent1 = new Intent(context,MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context,0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
}
My Alarm Service:
public class MyAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Next Activity:
public class NextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
A few things you need to do here. If the user force closes the app, you need to ensure that you start your service with START_STICKY so that the service restarts when the app is force closed.
In order to get the Service to start when the user has rebooted their phone, you will need your BroadcastReceiver to receive BOOT_COMPLETED which will then start the service.
Your service will then set the Alarm as per normal. You will need to store the time of the alarm you want to set somewhere. I use SharedPrefs (PreferenceManager.getDefaultSharedPreferences(getApplicationContext());) but I'm sure there are better methods.

Alarm Manager Not Showing Notifications

I am new to android and working on Notification Alarm Manager to show notification. I am on API 23.
The code I posted below is working perfectly but I cannot filgure why it is not notifying me?
Can Any one help me what is the error in it?
Thanks.
MainActivity
public class MainActivity extends AppCompatActivity {
Button b;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) this.findViewById(R.id.btn);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 30);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 34);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
AlarmBroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, AlarmService.class);
context.startService(startIntent);
}
}
AlarmService
public class AlarmService extends Service{
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
generarNotificacion();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void generarNotificacion(){
Intent resultIntent = new Intent(this.getApplicationContext(), MainActivity.class);
android.support.v4.app.NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.heart1)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.text));
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
Android Manifest
<uses-permission-sdk-23 android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".AlarmService"
android:enabled="true" />
<receiver android:name=".AlarmBroadcastReceiver"/>
It appears that you're trying to set an alarm for today, shortly in the future. However, months are zero-based, so a value of 11 is actually December. If you want November, the corresponding value is 10. A better option, though, is to use the class constant: Calendar.NOVEMBER.

I want to fire the notification with particular date time in android

In my Application I have Multiple events for every event I need to create one UILocalNotification for example like I want to say wishes on Fathers day,Mothers and some festivals. So I already I have the specific date now I want to fire it on the particular day please how to do this. I have already done for single UILocalNotification. Now I need for multiple fire dates.
If I comment the date it's firing on particular time. Now date with time is not working.
Now problem how to add multiple dates and time in same activity I want to fire the notifications.
Can anyone please help me.
MyView class
public class MyView extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar firingCal = Calendar.getInstance();
firingCal.set(Calendar.MONTH, 7);
firingCal.set(Calendar.YEAR, 2014);
firingCal.set(Calendar.DAY_OF_MONTH, 9);
firingCal.set(Calendar.HOUR_OF_DAY, 16);
firingCal.set(Calendar.MINUTE, 35);
firingCal.set(Calendar.SECOND, 0);
// MyView is my current Activity, and AlarmReceiver is the
// BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyView.this,
0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
* The following sets the Alarm in the specific time by getting the long
* value of the alarm date time which is in calendar object by calling
* the getTimeInMillis(). Since Alarm supports only long value , we're
* using this method.
*/
alarmManager.set(AlarmManager.RTC_WAKEUP, firingCal.getTimeInMillis(),
pendingIntent);
}
}
MyAlarmService class
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}

Alarm Manager & Broadcast receiver not stopping

I want to create notifications on multiple specific dates & time, which are stored in database. I can get Notifications on correct date and time, but what i noticed later is, that i also got notifications randomly on the next day. They keep cropping up whenever i restart the emulator.
So, it seems that i can't stop the Alarm manager or Broadcast receiver. I've tried with providing pendingIntent to alarmmanager's cancel method to no avail. I also use toggle button to enable/disable notification, but it has no effect
Below is my code.
MainActivity.java
PendingIntent pendingIntent;
AlarmManager alarmManager;
Button set, cancel;
MTPAdapter db;
ArrayList<TourPlan> arrDates;
ToggleButton toggle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
toggle = (ToggleButton) findViewById(R.id.toggleButton1);
// This function fetched data from DB
fetchDates();
set = (Button) findViewById(R.id.the_button);
cancel = (Button) findViewById(R.id.the_button_cancel);
cancel.setEnabled(false);
toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
Toast.makeText(getApplicationContext(), "Set",
Toast.LENGTH_SHORT).show();
setEvent();
} else {
alarmManager.cancel(pendingIntent);
MyReceiver.stopService(getApplicationContext());
}
}
});
} // end onCreate
public void setEvent() {
for (int i = 0; i < arrDates.size(); i++) {
// int id = arrDates.get().getId();
int year = Integer.parseInt(arrDates.get(i).getYear());
int month = Integer.parseInt(arrDates.get(i).getMonth());
int date = Integer.parseInt(arrDates.get(i).getDate());
int hour = Integer
.parseInt(firstStringer(arrDates.get(i).getTime()));
Log.v("Hour : ", "" + hour);
int minute = Integer.parseInt(stringer(arrDates.get(i).getTime()));
Log.v("minute : ", "" + minute);
int second = 00;
startAlarm(i, year, month, date, hour, minute, second);
}
}
public void startAlarm(int id, int year, int month, int date, int hour,
int minute, int second) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, date);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, id,
myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent);
}
}
MyAlarmService.java
public class MyAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ISFA")
.setStyle(
new NotificationCompat.BigTextStyle()
.bigText("Tour Planned for the Day"))
.setContentText("You have planned a tour for today")
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
MyReceiver.java (Broadcast receiver) :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
public static void stopService(Context context) {
Intent stopServiceIntent = new Intent(context, MyAlarmService.class);
context.stopService(stopServiceIntent);
}
}
Manifest file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
In Application tags,
<service
android:name="com.example.brodcastalarm.MyAlarmService"
android:enabled="true" />
<!-- THE BROADCAST RECIEVER WHICH MANAGES THE BROADCAST FOR NOTIFICATION -->
<receiver android:name="com.example.brodcastalarm.MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This is the Database structure.
I use subString methods to get hour and minutes.
Alarm manager needs to be manually disabled, so for doing so use code below, it will disable the alarm.
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), YourScheduleClass.class);
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
aManager.cancel(pIntent);

Show a toast (using alarmmanager)

I've a service that runs after android starts. I'd like show a toast every days at 9am. The problem is: how can I implement the code (alarmamanger within service)?
Start service after boot:
public class AutoStart extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.startatboot.UnUsedService");
context.startService(serviceIntent);
}
}
public class Service extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0); AlarmManager am = (AlarmManager) context.getSystemService (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyClass.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
Just replace your code with my code,
public class Service extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0); AlarmManager am = (AlarmManager) context.getSystemService (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
Now create a new class AlarmReceiver in the same package and add the following code to it.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
Now define it in the PendingIntent of the Alarm.
Add following code in the manifest file,
<receiver android:name=".AlarmReceiver" />
Now run your application. that's it. It will definitely show a toast at 9.
Let me know if it worked or not.

Categories

Resources