How can I schedule notification according to user input? - android

I've tried a bunch of things in order to notification worked well, but nothing is working properly... This is my NotificationPublisher class
public class NotificationPublisher extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
Intent intent = new Intent(this,CreateNewPvpFragment.class);
long[] pattern = {0,300,0};
PendingIntent pi = PendingIntent.getActivity(this,01234,intent,0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setContentTitle("PVP")
.setContentText("Verify your PVP")
.setVibrate(pattern)
.setAutoCancel(true);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(01234,mBuilder.build());
}
}
And here my NotificationReceiver class:
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,NotificationPublisher.class);
context.startService(service);
}
}
And finally my method in my Fragment
public void addReminder (int mYear, int mMonth, int mDay){
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,mYear);
c.set(Calendar.MONTH,mMonth);
c.set(Calendar.DAY_OF_MONTH,mDay);
c.set(Calendar.HOUR_OF_DAY,15);
c.set(Calendar.MINUTE,30);
c.set(Calendar.SECOND,0);
c.set(Calendar.AM_PM,Calendar.PM);
int alarmId = 001;
alarmId = Integer.parseInt(mDay+""+mMonth+"");
Intent intent = new Intent(getActivity(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(),alarmId,intent, 0);
AlarmManager am = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), pendingIntent);
}
This method its receiving values from the Datepicker dialog, according to user input.
Before, it was working only with the current day, but now neither with that

Related

Using AlarmManager to activate and deactivate silence mode

In my program, I am getting 2 dates from user. First date is for activating silence mode and the second date is deactivating it. For handling this issue, I have tried to use 2 different AlarmManager and 2 different BroadcastReceiver but I couldn't achieve it.
I can activate silence mode at the first date but I couldn't deactivate it. This a part of my code:
public class AddEvent extends AppCompatActivity {
private static PendingIntent silenceActivatorPendingIntent;
private static PendingIntent silenceDeactivatorPendingIntent;
private static AlarmManager manager1;
private static AlarmManager manager2;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent silenceActivatorIntent = new Intent(this, SilenceModeActivator.class);
Intent silenceDeactivatorIntent = new Intent(this, SilenceModeDeactivator.class);
silenceActivatorPendingIntent = PendingIntent.getBroadcast(this, 0, silenceActivatorIntent, 0);
silenceDeactivatorPendingIntent = PendingIntent.getBroadcast(this, 0, silenceDeactivatorIntent, 0);
manager2 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager1 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
}
public void addEvent(View view) {
GregorianCalendar targetStartDate = new GregorianCalendar(startYear, startMonth, startDay, startHour, startMinute, 0);
GregorianCalendar targetEndDate = new GregorianCalendar(endYear, endMonth, endDay, endHour, endMinute, 0);
manager1.set(AlarmManager.RTC_WAKEUP, targetStartDate.getTimeInMillis(), silenceActivatorPendingIntent);
manager2.set(AlarmManager.RTC_WAKEUP, targetEndDate.getTimeInMillis(), silenceDeactivatorPendingIntent);
}
public static void stopAlarm1() {
manager1.cancel(silenceActivatorPendingIntent);
}
public static void stopAlarm2() {
manager2.cancel(silenceDeactivatorPendingIntent);
}
}
addEvent is my button clicker method.
Silence Mode Activator:
public class SilenceModeActivator extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
activateSilentMode(context);
AddEvent.stopAlarm1();
}
public void activateSilentMode(Context context) {
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// Check if the notification policy access has been granted for the app.
if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
context.startActivity(intent);
}
mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
}
}
Silence Mode Deactivator:
public class SilenceModeDeactivator extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
deactivateSilentMode(context);
AddEvent.stopAlarm2();
}
public void deactivateSilentMode(Context context) {
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// Check if the notification policy access has been granted for the app.
if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
context.startActivity(intent);
}
mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
}
}
Do you have any idea about how I can fix this?
Thanks in advance.

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.

How can I prevent service restarting in Android?

I have a service to show notification at a specific time and one broadcastreceiver for starting this service. When the app is started, the service is started and shows notification and shows the service in app running on the device, but sometimes in the running app service is a Restarting and the message does not display.
my service code is:
public class NotificationService extends Service {
private boolean flag=false;
public static NotificationCompat.Builder mBuilder;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer timer=new Timer();
final Context context=getApplicationContext();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if(CheckTime()){
//Intent intent = new Intent(context, NotificationReciver.class);
//sendBroadcast(intent);
showNotification();
}
}
},0,(1000*60));
return START_NOT_STICKY;
}
private boolean CheckTime(){
final Context context=getBaseContext();
Calendar calendar=Calendar.getInstance();
int hour=calendar.get(Calendar.HOUR_OF_DAY);
int minute=calendar.get(Calendar.MINUTE);
if(hour==16 && minute==11){
return true;
}else {
return false;
}
}
private void showNotification() {
Context context=getApplicationContext();
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent=new Intent(context, QuestionActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(context,0,intent,0);
mBuilder = new NotificationCompat.Builder(context).
setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Feelinger")
.setContentText("How are you feeling today?")
.setSound(alarmSound)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setVibrate(new long[]{300, 200, 200, 200});
android.app.NotificationManager mNotificationManager = (android.app.NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(100, mBuilder.build());
}
and BroadcastReceiver code is:
public class NotificationManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,NotificationService.class));
}
How to solve this problem?
Write inside service
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
return START_NOT_STICKY;
}

Android: status bar notifications in specific time

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);

Categories

Resources