I am not able to update the app with API 26.
The following error appears in when I try to run the project
Error:
"ServerRunningNotification.java": error: cannot find symbol method
setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
This is my code snippet which having Error
Code:
public class ServerRunningNotification extends BroadcastReceiver {
private static final String TAG = ServerRunningNotification.class.getSimpleName();
private final int NOTIFICATIONID = 7890;
public String iptext;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive broadcast: " + intent.getAction());
if (intent.getAction().equals(FtpServerService.ACTION_STARTED)) {
setupNotification(context);
} else if (intent.getAction().equals(FtpServerService.ACTION_STOPPED)) {
clearNotification(context);
}
}
#SuppressWarnings("deprecation")
private void setupNotification(Context context) {
Log.d(TAG, "Setting up the notification");
// Get NotificationManager reference
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager) context.getSystemService(ns);
// get ip address
InetAddress address = FtpServerService.getLocalInetAddress();
if (address == null) {
Log.w(TAG, "Unable to retreive the local ip address");
return;
}
iptext = "ftp://" + address.getHostAddress() + ":"
+ Settings.getPortNumber() + "/";
// Instantiate a Notification
int icon = R.drawable.ftp_icon;
CharSequence tickerText = String.format(
context.getString(R.string.notif_server_starting), iptext);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
// Define Notification's message and Intent
CharSequence contentTitle = context.getString(R.string.notif_title);
CharSequence contentText = String.format(context.getString(R.string.notif_text),
iptext);
Intent notificationIntent = new Intent(context, FTP_Start_Stop.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification
.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// Pass Notification to NotificationManager
nm.notify(NOTIFICATIONID, notification);
Log.d(TAG, "Notication setup done");
}
private void clearNotification(Context context) {
Log.d(TAG, "Clearing the notifications");
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager) context.getSystemService(ns);
nm.cancelAll();
Log.d(TAG, "Cleared notification");
}
}
According to here, setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent) method was removed in Android M (API 23). So it won't work in API versions above 23.
Related
Android 13 New notification appears after old one notification clear. When first notification show then new notification received on onMessageReceived method but it will display if i have old notifiction cleared form notification bar. otherwise it will not showing on notification bar.
My FirebaseMessageingService class as below
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
//scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
sendRegistrationToServer(token);
}
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
private void sendNotification(String title,String messageBody) {
int uniqueCode=Prefs.getUniqueCode(getApplicationContext());
if(uniqueCode==1000){
uniqueCode=0;
}
Log.d("uniqueCode",uniqueCode+"");
Intent intent
= new Intent(this, LoginActivity.class);
// Assign channel ID
String channel_id = "Default";
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent
= PendingIntent.getActivity(
this, uniqueCode, intent,
PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Prefs.setUniqueCode(getApplicationContext(),uniqueCode+1);
NotificationCompat.Builder builder
= new NotificationCompat
.Builder(getApplicationContext(),
channel_id)
.setSmallIcon(R.drawable.applogo)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000,
1000, 1000})
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
builder = builder.setContentTitle(title)
.setContentText(messageBody)
.setSmallIcon(R.drawable.applogo)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody));
NotificationManager notificationManager
= (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT
>= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel
= new NotificationChannel(
channel_id, "Default channel",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(
notificationChannel);
}
notificationManager.notify(0, builder.build());
}
}
I'm trying to fix my code and I want to add notify on my App, but I don't know why it's not working.
This is notificaService.java:
public class notificaService extends BroadcastReceiver {
DatabaseHelper db;
String CHANNEL_ID = "150";
String id;
String KEY_TEXT_REPLY = "key_text_reply";
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
db = new DatabaseHelper (context);
String temperatura1, glicemia1, battito1, peso1;
temperatura1 = "temperatura";
glicemia1 = "glicemia";
battito1 = "battito";
peso1 = "peso";
//verify whether if user as inserted any record today
long reports = db.countRows(temperatura1) + db.countRows(glicemia1)
+ db.countRows(peso1) + db.countRows(battito1);
String haji1 = String.valueOf (reports);
Log.i("LALALALALALSERVICE", haji1);
//builder for the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
//as the user clicks on the intent, open MainActivity aka ReportFragment
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context, 0, myIntent, PendingIntent.FLAG_ONE_SHOT
);
Intent intent1 = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,0,intent1,PendingIntent.FLAG_ONE_SHOT);
//set notification features
builder.setContentTitle("Daily Reminder")
.setContentText("Remember to fill today's report")
.setSmallIcon(R.drawable.alarmclock)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(Color.BLUE)
.setAutoCancel(true)
//.setChannelId(id)
//.addAction(R.drawable.logout_icon, "SET TIME", resultPendingIntent)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//if no reports are recorded, trigger notification
if(reports == 0)
notificationManager.notify(1, builder.build());
}
}
This is Notifica.java, where I set the time for my notify:
public class Notifica extends AppCompatActivity {
private EditText edt_orario;
private Button btnInvio, btn_setOrario;
DatabaseHelper db = new DatabaseHelper(this);
Calendar calendar = Calendar.getInstance ( );
long reports;
String channel = "100";
private final boolean[] vibration = new boolean[1];
private NotificationManager notificationManager;
String KEY_TEXT_REPLY = "key_text_reply";
String CHANNEL_ID = "200";
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_notifica);
edt_orario=findViewById(R.id.edt_orario);
btn_setOrario=findViewById(R.id.btn_setOrario);
btnInvio=findViewById(R.id.btnInvio);
db = new DatabaseHelper (this);
String temperatura1, glicemia1, battito1, peso1;
temperatura1 = "temperatura";
glicemia1 = "glicemia";
battito1 = "battito";
peso1 = "peso";
reports = db.countRows(temperatura1) + db.countRows(glicemia1)
+ db.countRows(peso1) + db.countRows(battito1);
String haji1 = String.valueOf (reports);
Log.i("LALALALALAL", haji1);
//instatiate the notification manager
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
createNotificationChannel(CHANNEL_ID);
//create the channel through which the notification should communicate.
/*dataSpe = oggi.format (new Date());
cursor = db.viewDataOggi("peso",dataSpe);
cursor1 = db.viewDataOggi("temperatura",dataSpe);
cursor2 = db.viewDataOggi("glicemia", dataSpe);
cursor3 = db.viewDataOggi("battito", dataSpe);
Log.i("kkkkkkkkkkkk", " "+ cursor2.getCount());*/
//bottone per impostare l'orario in cui arriverà la notifica
btn_setOrario.setOnClickListener(new View.OnClickListener() {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
#Override
public void onClick(View v) {
TimePickerDialog timePickerDialog = new TimePickerDialog(Notifica.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String realMinute, realHour;
//controllo per inserire l'orario in formato leggibile
if (minute < 10) {
realMinute = "0" + minute;
} else {
realMinute = String.valueOf (minute);
}
if (hourOfDay < 10) {
realHour = "0" + hourOfDay;
} else {
realHour = String.valueOf (hourOfDay);
}
edt_orario.setText (realHour + ":" + realMinute);
}
}, hour, min, true);
timePickerDialog.show();
}
});
btnInvio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//se non c'è nessun report inserito per la data di oggi, allora ...
//if ((cursor.getCount() == 0) || (cursor1.getCount() == 0) || (cursor2.getCount() == 0) || (cursor3.getCount() == 0)) {
//classe per gestire lo scatto della notifica alla stessa ora tutti i giorni
//if (reports == 0) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent;
PendingIntent pendingIntent;
//impostazione dell'orario in cui scatterà la notifica
int hour, min;
hour = Integer.parseInt (edt_orario.getText ( ).toString ( ).substring (0, 2));
min = Integer.parseInt (edt_orario.getText ( ).toString ( ).substring (3));
Calendar c = Calendar.getInstance ( );
c.set (Calendar.HOUR_OF_DAY, hour);
c.set (Calendar.MINUTE, min);
c.set (Calendar.SECOND, 1);
//passo la gestione della notifica al NotificationService tramite l'intent
intent = new Intent (Notifica.this, notificaService.class);
//gestisco lo scatto della notifica tramite broadcast
pendingIntent = PendingIntent.getBroadcast (Notifica.this, 0, intent, 0);
alarmManager.setInexactRepeating (alarmManager.RTC_WAKEUP, c.getTimeInMillis ( ), AlarmManager.INTERVAL_DAY, pendingIntent);
Toast.makeText (getApplicationContext ( ), "Impostazioni salvate", Toast.LENGTH_SHORT).show ( );
}
// }
}
);
}
/*#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
}
*/
#RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel (String id){
int importanza = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(id, "info", importanza);
notificationChannel.setDescription("info");
notificationChannel.enableVibration(true);
notificationChannel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(notificationChannel);
}
}
In my Db everything it's working because I have seen it thanks to Log. So I have no idea where I'm making the mistake.
Thank you for your help!
The following code will create a notification which you can set the title and body :
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
To show the notification, all you need to do is call the function :
showNotification(getApplicationContext(),"This is the title", "This is the body", getIntent());
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.
Sorry for my english. I use parse.com i want create custom sound when i get push. When I send a push, the phone just vibrates. There is no sound and the message does not show too.
This is my sound: image (i have not 15 reputation)
code:
public class MyBroadcastReceiver extends ParsePushBroadcastReceiver {
private int NOTIFICATION_ID = 1;
#Override
public void onPushOpen(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.putExtras(intent.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#Override
public void onReceive(Context context, Intent intent) {
try{
String jsonData = intent.getExtras().getString("com.parse.Data");
JSONObject json = new JSONObject(jsonData);
String title = null;
if(json.has("title")) {
title = json.getString("title");
}
String message = null;
if(json.has("alert")) {
message = json.getString("alert");
}
if(message != null) {
generateNotification(context, title, message);
}
} catch(Exception e) {
Log.e("NOTIF ERROR", e.toString());
}
}
private void generateNotification(Context context, String title, String message) {
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager mNotifM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(title == null) {
title = context.getResources().getString(R.string.app_name);
}
final NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.addAction(0, "View", contentIntent)
.setAutoCancel(true)
.setDefaults(new NotificationCompat().DEFAULT_VIBRATE)
.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/beep1.mp3"));
mBuilder.setContentIntent(contentIntent);
mNotifM.notify(NOTIFICATION_ID, mBuilder.build());
}
}
UPD:
This is not work too, i have standart sound
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "beep1.mp3");
return n;
}
UPD:
I pu mp3 to folder res/raw/beep1.mp3 and use ("android.resource://" + context.getPackageName() + R.raw.beep1); but its not help
Assuming that you have your own subclass of ParsePushBroadcastReceiver and you declared it in Manifest, I recommend you to put your mp3 file in the /raw folder and to change your getNotification() method as follows
#Override
protected Notification getNotification(Context context, Intent intent) {
Notification n = super.getNotification(context, intent);
n.defaults = 2;
n.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.beep1);
return n;
}
If you want just to change sound the getNotification() method is the only one you need to overrid
Its work for me! Import: sound mus be here: res/raw/beep1.mp3 and path like this "android.resource://" + context.getPackageName() +"/"+ "R.raw.beep1"
#Override
public void onReceive(Context context, Intent intent) {
try {
JSONObject json = new JSONObject(intent.getExtras().getString(
"com.parse.Data"));
alert = json.getString("alert").toString();
} catch (JSONException e) {}
notifySound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_launcher); //You can change your icon
mBuilder.setContentText(alert);
mBuilder.setContentTitle("Пользователь");
mBuilder.setSound(Uri.parse("android.resource://" + context.getPackageName() +"/"+ R.raw.beep1));
mBuilder.setAutoCancel(true);
resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, mBuilder.build());
}
}
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();