I am trying to send the notification via service. The time of the notification is set from the database table where I have date, time etc columns. So when System.currentTimeMillis is equal to the time from database column I am trying to send the notification to the user. However my implementation doesn't work, could someone please help me? Thanks in advance
Here is my Service file
public class MyService extends Service {
private NotificationManager notificationManager;
private DBHelper dbHelper;
private SQLiteDatabase db;
#Override
public void onCreate() {
Log.i("myLOgs", "Service: onCreate()");
super.onCreate();
dbHelper = new DBHelper(this);
db = dbHelper.getReadableDatabase();
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("myLOgs", "Service: onStartCommand()");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String currentDateString = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH-mm");
Date time = new Date();
String currentTimeString = timeFormat.format(time);
String[] columns = {DBHelper.DATE, DBHelper.TIME, DBHelper.EVENT};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
do {
String dateString = cursor.getString(cursor.getColumnIndex(DBHelper.DATE));
String timeString = cursor.getString(cursor.getColumnIndex(DBHelper.TIME));
String eventString = cursor.getString(cursor.getColumnIndex(DBHelper.EVENT));
if((currentDateString.equals(dateString)) && (currentTimeString.equals(timeString))) {
Notification notification = new Notification(R.drawable.ic_launcher, eventString, System.currentTimeMillis());
}
if(cursor.moveToLast()) {
cursor.moveToFirst();
}
}while(true);
//return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Simply you can use this method for giving notification from service.
Just make this method as member of your service class and then you can call this method from service class onStartCommand or wherever you needed.
Fully working i used in my project...
private int notificationID = 100;
private void giveNotification(String notificationTitle, String bodytext)
{
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, DeliveryReport.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationID, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, bodytext, pendingIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationID++, notification);
}
To send notification you need to use pending intent
sample code for notification
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notification = new Intent(this, MainActivity.class);
notification.putExtra("message", message);
PendingIntent pIntent = PendingIntent.getActivity(this, 0,
notification, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.logo)
.setContentTitle("sample").setContentText(message)
.setAutoCancel(true);
mBuilder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(new Random().nextInt(),
mBuilder.getNotification());
Ringtone r = RingtoneManager.getRingtone(context, soundUri);
r.play();
Related
I've created a service which consult notes if they are in recicle bin, it have to run once a day but with handler I think it will drain too much battery, So I need you help How can I do a task once a day without drain battery or other thing that's not a handler ?
When the app is launched the NotesApplication is created and start the NotesService class, it should be executing all day but it will drain battery, so I need to execute once a day
NotesApplication
public class NotesApplication extends Application {
String TAG = "NotesApplication";
Intent intent;
#Override
public void onCreate() {
// TODO: Implement this method
super.onCreate();
Log.d(TAG, "Application created");
intent = new Intent(getApplicationContext(), NotesService.class);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
Log.d(TAG, "Foreground service started");
getApplicationContext().startForegroundService(intent);
}else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
Log.d(TAG, "Service started");
getApplicationContext().startService(intent);
}
}
Notes Service
public class NotesService extends Service {
ArrayList<Notes> listNotas;
String TAG = "NotesService";
SQLiteHelperConnection conn;
#Override
public void onCreate()
{
// TODO: Implement this method
super.onCreate();
Log.d(TAG, "Notes service created");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
final NotificationManager mNotific= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Axco";
String description = "Service";
int importance = NotificationManager.IMPORTANCE_MIN;
final String ChannelID="Service Channel";
NotificationChannel mChannel = new NotificationChannel(ChannelID, name, importance);
mChannel.setDescription(description);
mChannel.setLightColor(ThemeClass.getColor());
mChannel.canShowBadge();
mChannel.setShowBadge(true);
mNotific.createNotificationChannel(mChannel);
final int code = 101;
String body= "Service Running";
Notification notification = new Notification.Builder(this, ChannelID)
.setContentTitle(getPackageName())
.setContentText(body)
.setBadgeIconType(R.drawable.ic_launcher)
.setNumber(1)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.build();
startForeground(code, notification);
}
conn = new SQLiteHelperConnection(this, "db_notas.db", null, 1);
listNotas = new ArrayList<Notes>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO: Implement this method
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
final NotificationManager mNotific= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "Axco";
String description = "Service";
int importance = NotificationManager.IMPORTANCE_MIN;
final String ChannelID="Service Channel";
NotificationChannel mChannel = new NotificationChannel(ChannelID, name, importance);
mChannel.setDescription(description);
mChannel.setLightColor(ThemeClass.getColor());
mChannel.canShowBadge();
mChannel.setShowBadge(true);
mNotific.createNotificationChannel(mChannel);
final int code = 101;
String body= "Service Running";
Notification notification = new Notification.Builder(this, ChannelID)
.setContentTitle(getPackageName())
.setContentText(body)
.setBadgeIconType(R.drawable.ic_launcher)
.setNumber(1)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.build();
startForeground(code, notification);
}
final Handler handler = new Handler();
Runnable runnable = new Runnable(){
#Override
public void run()
{
// TODO: Implement this method
Log.d(TAG, "Service running");
listNotas.clear();
consult();
check();
handler.postDelayed(this, 15000);
}
};
handler.post(runnable);
return Service.START_STICKY;
}
private void consult(){
Log.d(TAG, "Consulting...");
SQLiteDatabase db = conn.getReadableDatabase();
Notes notas = null;
Cursor cursor = db.rawQuery("SELECT * FROM "+Utilities.TABLA_NOTA, null);
while (cursor.moveToNext()) {
notas = new Notes();
notas.setId(cursor.getString(0));
notas.setLastModified(cursor.getString(5));
notas.setLastModifiedDate(cursor.getString(7));
boolean a = Boolean.valueOf(cursor.getString(4));
if(a){
listNotas.add(notas);
}
}
}
private void check(){
//Do something
}
private void deleteNote(int position){
SQLiteDatabase db = conn.getWritableDatabase();
String[] parametros = {listNotas.get(position).getId()};
db.delete(Utilities.TABLA_NOTA, Utilities.ID+"=?", parametros);
listNotas.remove(position);
}
#Override
public IBinder onBind(Intent p1){
// TODO: Implement this method
return null;
}
Using Alarm Manager is efficient.
See implementation
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i= new Intent(context, AlarmManagerBroadcastReceiver.class);
//intent.putExtra(something you want to put);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// check if it is more than 11 am. if so set alarm for next day
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) {
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
// everyday at 11 am
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
// alarm set
Finally create a broadcast receiver to do the work you want.
I have an arrayList in the MainActivity, and I'm using alarmManager to show notifications when the app is closed. I don't know how I can use that arraylist in the BroadcastReceiver "inside onReceive() method" and get data from that arraylist to show it in the Notifications. I also want to be able to remove the element from the arraylist that has already been shown in the notification.
anyway this my code, I hope you can help me !
-MainActivity :
NotificationManager mNotificationManager;
int NOTIFICATION_ID = 0;
private static final String ACTION_NOTIFY = "com.example.android.standup.ACTION_NOTIFY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent notifyIntent = new Intent(ACTION_NOTIFY);
final PendingIntent notifyPendingIntent = PendingIntent.getBroadcast
(this, NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
ToggleButton toggleButton = findViewById(R.id.alarmToggle);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
long triggerTime = SystemClock.elapsedRealtime()+10000;
long repeatInterval = 180000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, repeatInterval, notifyPendingIntent);
}else {
mNotificationManager.cancelAll();
alarmManager.cancel(notifyPendingIntent);
}
}
});
}
AlarmReceiver Class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent contentIntent = new Intent(context, MainActivity.class);
PendingIntent contentPendingIntent = PendingIntent.getActivity
(context, createID(), contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Hello")
.setContentText("Notification Text")
.setContentIntent(contentPendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
notificationManager.notify(createID(), builder.build());
}
public int createID(){
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
return id;
}
}
Thank you !
I am new on android. I want to show notification on a particular date and time(For e.g on date 9 September 2017 on time 10:00 AM) in my app. I am using alarm manager but it does not work properly.
Please tell me the proper way.
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2017);
calendar.set(Calendar.MONTH, 9);
calendar.set(Calendar.DAY_OF_MONTH, 9);
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent inn = new Intent(MainActivity.this,AlarmActivity.class);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), 0,inn, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), displayIntent);
}
AlarmActivity
public class AlarmActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content_alarm);
final Intent notificationIntent = new Intent(this, AlarmActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(AlarmActivity.this, 0, notificationIntent, 0);
Notification notification1 = new Notification.Builder(AlarmActivity.this)
.setContentTitle("Notification")
.setContentText("Get Notigication")
.setContentIntent(contentIntent).setWhen(System.currentTimeMillis())
.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1, notification1);
}
Manifest
Permission
In order to trigger alarm you have to use WakefulBroadcastReceiver from where you will trigger a service that will generate notification in you activity.
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Then you will create a service like this.
public class AlarmService extends IntentService {
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
contentId = intent.getStringExtra("id");
String title = intent.getStringExtra("title");
String subtitle = intent.getStringExtra("subtitle");
sendNotification(title, subtitle);
}
public void sendNotification(String title, String subtitle) {
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.reminder_notification_view);
contentView.setInt(R.id.layout, "setBackgroundColor",
Color.WHITE);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, subtitle);
notification.contentView = contentView;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notification.contentIntent = PendingIntent.getActivity(this, someRandomId,
intent, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL; //Do not clear the notification
notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
notification.defaults |= Notification.DEFAULT_SOUND; // Sound
mNotificationManager.notify(someRandomId, notification);
}
}
I created a method to send a notification to the user named sendNotification () using NotificationCompat.Builder and NotificationManager.
I need this notification to be posted at a fixed interval of 24 hours or even at a specific time, for example every day at 07:00 AM, which in this case would result in the same 24 hours, which may be adjusted by the user in the future.
It seems to me that with the public class AlarmManager it is possible to perform this procedure, but I am not sure if I have to create a service or if it would be the service itself.
How could this notification be done within this 24-hour ?
public void setLocalNotification(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(this, LocalNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 99, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Log.d("TAG ","LocalNotification Start");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pendingIntent);
}
public class LocalNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TUS-NOTAS ", "LocalNotification Receiver");
Intent service1 = new Intent(context, ShowNotificationService.class);
context.startService(service1);
}
}
public class ShowNotificationService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private final static String TAG = "ShowNotification";
public ShowNotificationService()
{
super("ServiceNotification");
}
public ShowNotificationService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
Context context = this.getApplicationContext();
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, SplashActivity.class);
pendingIntent = PendingIntent.getActivity(context,99, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getResources().getString(R.string.app_name));
builder.setVibrate(new long[] { 200, 200});
builder.setSound(uri);
if (Global.getStringKey(getApplicationContext(), Definitions.LANGUAGE_VALUE).equals("en"))
{
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("We miss you!"));
builder.setContentText("You have not added any notes recently.");
}else if (Global.getStringKey(getApplicationContext(),Definitions.LANGUAGE_VALUE).equals("es"))
{
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("Te extrañamos!"));
builder.setContentText("No has agregado notas recientemente.");
}
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_logo_app);
builder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Log.d("TUS-NOTAS"," LocalNotification Service");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
}
}
0 0 7 1/1 * ? *
This is a cron statement made from http://www.cronmaker.com/. You can use this in a cron job that executes everyday at 7 am.
The implementation of the notification sending does actually work if I send it from Activity, but nothing happens if I send from Service. Can anyone suggest possible solutions? Thanks
Here is my Service implementation..........
public class MyService extends Service {
private NotificationManager notificationManager;
private DBHelper dbHelper;
private SQLiteDatabase db;
private Context mContext = this;
private int notificationID = 100;
#Override
public void onCreate() {
Log.i("myLOgs", "Service: onCreate()");
super.onCreate();
dbHelper = new DBHelper(this);
db = dbHelper.getWritableDatabase();
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("myLOgs", "Service: onStartCommand()");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String currentDateString = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH-mm");
Date time = new Date();
String currentTimeString = timeFormat.format(time);
String[] columns = {DBHelper.DATE, DBHelper.TIME, DBHelper.EVENT};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
do {
String dateString = cursor.getString(cursor.getColumnIndex(DBHelper.DATE));
String timeString = cursor.getString(cursor.getColumnIndex(DBHelper.TIME));
String eventString = cursor.getString(cursor.getColumnIndex(DBHelper.EVENT));
boolean dateCompare = currentDateString.equals(dateString);
boolean timeCompare = currentTimeString.equals(timeString);
if((dateCompare) && (timeCompare)) {
Notify(eventString, "message");
}
if(cursor.moveToLast()) {
cursor.moveToFirst();
}
}while(true);
//return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void Notify(String notificationTitle, String bodytext){
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationID, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, bodytext, pendingIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationID++, notification);
}
}