I'm developing my first Android app, Todo List, and i have to schedule notification at custom date(in 24 hr format) & time with date & timepicker.
Notifications don't appear as scheduled !
Can someone tell me what is the problem with my code?
My code :
Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.todo.amine.mytodo"
android:versionCode="2"
android:versionName="1.1">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyAlarm"
android:enabled="true" />
<receiver android:name=".MyReceiver">
</receiver>
</application>
</manifest>
CreateNotify Method :
public void createNotify(int month, int year, int day, int hour, int m){
Calendar c = Calendar.getInstance();
Date temp = c.getTime();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
/** calendar.set(Calendar.AM_PM,Calendar.PM);**/
Date pm = calendar.getTime();
if(pm.after(temp))
{
Intent myIntent = new Intent(Main.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(Main.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
}
MyAlarm.class
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyAlarm 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(),Main.class);
Notification notification = new Notification(R.drawable.ic_appxhdpi,"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();
}
}
MyReceive.class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarm.class);
context.startService(service1);
}
}
Related
I implemented some notifications that fire on specific date and time. My code works if phone is not rebooted after app installation, but if I reboot the phone the notifiction does not fire. I tried many methods proposed by other developers, but nothing changed. Is it possible to restart notification service automatically on system reboot?
BootService.java
package com.example.is2_app.utility;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import java.util.Calendar;
import static java.util.Calendar.APRIL;
public class BootService extends JobIntentService {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
intent = new Intent(this, ReminderBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR,-1);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 9);
calendar.set(Calendar.SECOND, 40);
if(calendar.getTimeInMillis()>System.currentTimeMillis()) {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
}
}
ReminderBroadcast.java
package com.example.is2_app.utility;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import com.example.is2_app.MainActivity;
import com.example.is2_app.R;
public class ReminderBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
void showNotification(Context context) {
String CHANNEL_ID = "your_name";// The id of the channel.
CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
NotificationCompat.Builder mBuilder;
Intent notificationIntent = new Intent(context, MainActivity.class);
long when = System.currentTimeMillis();
Bundle bundle = new Bundle();
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startService(notificationIntent);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_candida)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID);
} else {
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_candida)
.setPriority(Notification.PRIORITY_DEFAULT);
}
mBuilder.setContentTitle(context.getString(R.string.spazzatura));
mBuilder.setContentIntent(contentIntent);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.spazzatura_residuo)));
mBuilder.setContentText(context.getString(R.string.spazzatura_residuo));
mBuilder.setAutoCancel(true).setWhen(when);
mNotificationManager.notify(1, mBuilder.build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.is2_app">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".global.Global"
android:allowBackup="true"
android:configChanges="locale|orientation|keyboardHidden|screenSize"
android:icon="#mipmap/ic_launcher_candida"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_candida_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<service
android:name=".utility.BootService"
android:enabled="true"
android:exported="true" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".utility.ReminderBroadcast"
android:permission = "android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
</application>
</manifest>
I am trying to experiment with services, and I found this example:
Alarm Manager Example.
I tried using the accepted answer, and the changes AndroidDev suggested, but I cant get it to work. Based on the fact that none of my Log messages appear, I think that the Service isn't called.
My onCreate method is this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent serviceIntent = new Intent(this, YourService.class);
startService(serviceIntent);
Vibrator v=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
the Service is this:
package habos.alarmtest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class YourService extends Service
{
Alarm alarm = new Alarm();
String tag="Babis service";
public void onCreate()
{
super.onCreate();
Log.i(tag, "oncreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(tag, "onstartcommand");
alarm.setAlarm(this);
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId)
{
alarm.setAlarm(this);
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
The onStart method is deprecated, but onStartCommand should work.
the manifest is this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="habos.alarmtest">
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".Alarm" android:exported="true">
<intent-filter>
<action android:name="habos.START_ALARM" >
</action>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
and the alarm is this
package habos.alarmtest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import android.os.Vibrator;
public class Alarm extends BroadcastReceiver
{
String tag="Babis alarm";
#Override
public void onReceive(Context context, Intent intent)
{
Log.i(tag, "onreceive");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
Vibrator v=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
wl.release();
}
public void setAlarm(Context context)
{
Log.i(tag,"setalarm");
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("mypackage.START_ALARM");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 30,pi); // Millisec * Second * Minute
}
public void cancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
added 2 more Logs, before and after the startService,the logcat is here:
https://www.dropbox.com/s/0ksdrfzyjb0qafe/logcat.txt?dl=0
(sorry I didn't paste it directly here, the code block didn't work for some reason)
I followed this tutorial for Repeating Alarm Example in Android using AlarmManager: http://javatechig.com/android/repeat-alarm-example-in-android.
I want to start an alarm which will trigger an intent service every 10 seconds. But it doesn't work, if there is someone who can help me.
MainActivity code:
package subhi.com.broadcast2;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MainActivity.this, MyService.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
});
findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAt10();
}
});
}
public void start() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancel() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
public void startAt10() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 1000 * 60 * 20;
/* Set the alarm to start at 10:30 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 30);
/* Repeating on every 20 minutes interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, pendingIntent);
}
}
The AlarmReciver code, which will start the IntentService:
package subhi.com.broadcast2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by subhi on 2/20/2016.
*/
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
//Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
Intent intent2=new Intent(context,MyService.class);
context.startService(intent);
}
}
The MyService code:
package subhi.com.broadcast2;
import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by subhi on 2/20/2016.
*/
public class MyService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public MyService() {
super("My_Worker_Thread");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"Service Started....",Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"Service Stopped....",Toast.LENGTH_LONG).show();
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getApplicationContext(),"Good",Toast.LENGTH_LONG).show();
synchronized (this){
int count=0;
while (count<10) {
try {
wait(3000);
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Finally the manifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="subhi.com.broadcast2">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".MyService">
</service>
</application>
</manifest>
The broadcast receiver is having a BOOT_COMPLETED intent filter. Thus the receiver will only receive a broadcast on boot complete. Instead use your MyService intent service in the pending intent as follows
PendingIntent intent = PendingIntent.getService(context, 0, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);
I am making notification bar in my app and this is my code :
MainActivity:
package com.example.notificationservicedemo;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnClickListener {
EditText editMsg;
DatePicker datePicker;
TimePicker timePicker;
Button btnSetNotification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editMsg = (EditText) findViewById(R.id.editText1);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
btnSetNotification = (Button) findViewById(R.id.buttonSetNotification);
btnSetNotification.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View view) {
Intent intent = new Intent();
// TODO Auto-generated method stub
switch(view.getId()){
case R.id.buttonSetNotification:
String message=editMsg.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, datePicker.getMonth());
calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
calendar.set(Calendar.YEAR, datePicker.getYear());
calendar.set(Calendar.HOUR, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentHour());
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
intent.setClass(this, MyNotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
//startService(intent);
break;
}
}
}
MyNotificationService:
package com.example.notificationservicedemo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyNotificationService 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();
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(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "OnStart()", Toast.LENGTH_SHORT).show();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent= new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(R.drawable.ic_launcher, "Bla bla bla", System.currentTimeMillis());
String contentTitle="Title";
String contentText="This is your message";
notification.setLatestEventInfo(this, contentTitle, contentText, pendingIntent);
notificationManager.notify(123, notification);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notificationservicedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.notificationservicedemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.notificationservicedemo.MyNotificationService"></service>
</application>
</manifest>
Problem is that when I pick time when notification has to come up I press my button to save and then notification comes up immediately it ignores my timePicker and datePicker. What is the peoblem?
This is my solution for launch a notification on android :
public class MyNotification {
private NotificationManager nm;
private Notification nf;
private int notification_id;
public MyNotification(Context context, Class<?> cls, int icon, CharSequence tickerText, CharSequence title, CharSequence text, int notification_id) {
nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancelAll();
Intent activity = new Intent(context, cls);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, activity, 0);
Notification.Builder builder = new Notification.Builder(context);
builder.setContentIntent(contentIntent); //-> Activity open after click
builder.setAutoCancel(true);
builder.setSmallIcon(icon);
builder.setWhen(System.currentTimeMillis());
builder.setTicker(tickerText);
builder.setContentTitle(title);
builder.setContentText(text);
//builder.setSound(Uri.parse("android.resource://"+this.getPackageName()+R.raw.good)); //-> Song
//builder.setContent(new RemoteViews(getPackageName(), R.layout.note)); //-> Layout
//builder.setVibrate(new long[]{0, 100, 25, 100}); // -> Vibration
Notification nf = builder.getNotification();
this.nf = nf;
this.notification_id = notification_id;
}
public void show() {
this.nm.notify(notification_id, nf);
}
}
I hope i have helped you!
I am making an alarm application. It's working with some hardcoded values like
calendar.add(Calendar.SECOND,30);
after 30 second alarm is firing but it's not working with
cal.set(Calendar.AM_PM,Calendar.PM);
cal.set(Calendar.MONTH,8);
cal.set(Calendar.YEAR,2011);
cal.set(Calendar.DAY_OF_MONTH,4);
cal.set(Calendar.HOUR_OF_DAY,5);
cal.set(Calendar.MINUTE,30);
Here is my whole code:
........Activity class..................
public class SampleAlarm1Activity extends Activity {
public Context context;
private boolean alarmstarted=true;
Button setalarm;
Button start;
Button cancel;
Edit Text year;
EditText month;
EditText date;
EditText hour;
EditText minute;
Intent i;
PendingIntent pi;
AlarmManager am;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context=getApplicationContext();
setalarm=(Button)findViewById(R.id.setalarm);
start=(Button) findViewById(R.id.start);
cancel=(Button)findViewById(R.id.cancelalarm);
month=(EditText)findViewById(R.id.month);
date=(EditText)findViewById(R.id.date);
hour=(EditText)findViewById(R.id.hour);
minute=(EditText)findViewById(R.id.minute);
setalarm.setOnClickListener(setalarmListener);
start.setOnClickListener(startalarmListener);
cancel.setOnClickListener(cancelalarm);
start.setVisibility(android.view.View.INVISIBLE);
month.setVisibility(android.view.View.INVISIBLE);
date.setVisibility(android.view.View.INVISIBLE);
hour.setVisibility(android.view.View.INVISIBLE);
minute.setVisibility(android.view.View.INVISIBLE);
}
private OnClickListener setalarmListener=new OnClickListener() {
#Override
public void onClick(View v) {
month.setVisibility(android.view.View.VISIBLE);
date.setVisibility(android.view.View.VISIBLE);
hour.setVisibility(android.view.View.VISIBLE);
minute.setVisibility(android.view.View.VISIBLE);
start.setVisibility(android.view.View.VISIBLE);
}
};
private OnClickListener startalarmListener=new OnClickListener() {
#Override
public void onClick(View v) {
int mon = 0,dat = 0,hr = 0,min = 0;
try{
String mon2=month.getText().toString();
System.out.println("month string entered::::::::::"+mon2);
mon=Integer.parseInt(mon2);
System.out.println("month int valuereturn entered::::::::::"+mon);
String dat2=date.getText().toString();
dat=Integer.parseInt(dat2);
System.out.println("date entered::::::::::"+dat);
String hr2=hour.getText().toString();
hr=Integer.parseInt(hr2);
System.out.println("hour entered::::::::::"+hr);
String min2=minute.getText().toString();
min=Integer.parseInt(min2);
System.out.println("minute entered::::::::::"+min);
}
catch(NumberFormatException exc){
System.out.println("exceptin is :"+exc);
}
Calendar cal=Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.AM_PM,Calendar.PM);
cal.set(Calendar.MONTH,mon);
System.out.println("month string entered::::::::::"+mon);
cal.set(Calendar.YEAR,2011);
cal.set(Calendar.DAY_OF_MONTH,dat);
System.out.println("date string entered::::::::::"+dat);
cal.set(Calendar.HOUR_OF_DAY,hr);
System.out.println("hour entered::::::::::"+hr);
cal.set(Calendar.MINUTE,min);
System.out.println("minute entered::::::::::"+min);
i = new Intent(SampleAlarm1Activity.this, AlarmReceiver.class);
pi=PendingIntent.getBroadcast(SampleAlarm1Activity.this, 0, i, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pi);
System.out.println("alarm on in activity ");
Toast.makeText(context, "alarm on activity", Toast.LENGTH_SHORT).show();
}
};
private OnClickListener cancelalarm=new OnClickListener() {
#Override
public void onClick(View v) {
if(alarmstarted)
try{
am.cancel(pi);
}catch(Exception e){
System.out.println("alarm not started"+e);
}
System.out.println("alarm cancel ");
Toast.makeText(context, "alarm cancel", Toast.LENGTH_SHORT).show();
}
};
}
broadcast receiver code....in same package ...........................................
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
System.out.println("alarm start");
Toast.makeText(context, "alarm is working",Toast.LENGTH_SHORT).show();
}
}
Manifest file..................................
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.SampleAlarm"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.SET_ALARM"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"></uses-permission>
<uses-permission android:name="android.permission.SET_TIME"></uses-permission>
<uses-permission android:name="android.permission.SET_TIME_ZONE"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleAlarm1Activity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver"></receiver>
</application>
</manifest>
I had make the same application but I had select the time from Time Picker but you can put your own time. Here I post my sample application classes. It may be help you..
SampleReminderActivity.java
package com.reminder;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SampleReminderActivity extends Activity {
private Button btn = null;
private AlarmManager alarmManager = null;
Calendar cal = Calendar.getInstance();
private Calendar calDay = Calendar.getInstance();
private Calendar dateStart = Calendar.getInstance();
static final int DIALOG_TIME = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
btn = (Button) findViewById(R.id.btnClick);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showDialog(DIALOG_TIME);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id){
case DIALOG_TIME:
dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
// c.clear();
c.set(Calendar.YEAR, hourOfDay);
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
Log.d("SampleRemainder", "Before Intent");
Intent intent = new Intent(SampleRemainderActivity.this,AlarmReceiver.class);
// startActivity(intent);
Log.d("SampleRemainder", "After Intent");
Log.d("SampleRemainder", "Before PendingIntent");
PendingIntent pi = PendingIntent.getBroadcast(SampleRemainderActivity.this, 0, intent, 0);
Log.d("SampleRemainder", "After PendingIntent");
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
Toast.makeText(SampleRemainderActivity.this, "Alarm has been set..", Toast.LENGTH_LONG).show();
}
},cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),false);
Log.d("SampleRemainder", "get cal Hour **" + cal.get(Calendar.HOUR_OF_DAY));
Log.d("SampleRemainder", "get cal Minute **" + cal.get(Calendar.MINUTE));
break;
}
return dialog;
}
}
AlarmReceiver.java
package com.reminder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.d("AlarmReceiver","in AlarmReceiver"+ context.toString());
Intent i = new Intent(context, AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
AlarmActivity.java
package com.reminder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
public class AlarmActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
Log.d("AlarmActivity","in AlarmActivity");
super.onCreate(savedInstanceState);
new AlertDialog.Builder(AlarmActivity.this).setTitle("Task").setMessage("Time to wake up").setPositiveButton("ok", new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
AlarmActivity.this.finish();
}
}).create().show();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button
android:id="#+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"
/>
</LinearLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.reminder"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleReminderActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AlarmActivity"></activity>
<receiver android:name="com.reminder.AlarmReceiver" android:process=":remote"></receiver>
</application>
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Hi friend my problem is solved.
Note: use
cal.set(Calendar.AM_PM,Calendar.AM or PM);
and cal.set(Calendar.HOUR,hour); for 12 hour format.
otherwise use only cal.set(Calendar.HOUR_OF_DAY, hour) for 24 hour format.
Other important thing i was doing mistake.
cal.set(Calendar.MONTH, month);
I was using 8 for august but it should be 7.
Actualy For January constant value is 0.
Thanks for your attention.