Sending the notifications from service - java

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

Related

notify not working on android studio ( API 27, ANDROID 8.1.0)

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

android service always running and notify user when needed

I need a service to make a notification whenever the user is in a moving car.
I use ActivityRecognition to find out when the user is in a car.the issue is I need my service to run even when the app is destroyed or removed by the user.
I tried running the service on a different process but after a few minutes the service stops working.I also tried using foreground service but I had the same issue with that to.
this is my service class.
public class SpeedCheckerService extends Service {
private final String CHANNEL_ID = "my_channel";
private static SpeedCheckerService speedCheckerService;
private ActivityRecognitionClient mActivityRecognitionClient;
private boolean started = false;
Date lastNotification;
CountDownTimer countDownTimer;
Intent intent;
#Override
public void onCreate() {
createNotificationChannel();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
this.intent=intent;
countDownTimer = new CountDownTimer(99999999,1000 * 60 * 1) {
#Override
public void onTick(long l) {
recognizeActivity();
}
#Override
public void onFinish() {
countDownTimer.start();
}
}.start();
return START_STICKY;
}
String detectedActivitiesToJson(ArrayList<DetectedActivity> detectedActivitiesList) {
Type type = new TypeToken<ArrayList<DetectedActivity>>() {}.getType();
System.out.println(detectedActivitiesList.toString());
if ((detectedActivitiesList.size()>=1)&&(detectedActivitiesList.get(0).getType() == DetectedActivity.STILL) && (detectedActivitiesList.get(0).getConfidence()) >= 60){
if(lastNotification!=null){
Calendar calendar = Calendar.getInstance();
calendar.setTime(lastNotification);
calendar.add(Calendar.MINUTE,5);
Date newDate = calendar.getTime();
calendar.clear();
System.out.println(lastNotification.toString());
System.out.println(newDate.toString());
if(newDate.after(calendar.getTime()) == true)
return null;
}
speedCheckerService.makeNotification();
lastNotification = Calendar.getInstance().getTime();
}
return new Gson().toJson(detectedActivitiesList, type);
}
public void makeNotification() {
createNotificationChannel();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("title")
.setContentText("text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.mapbox_logo_icon)
.setColor(Color.parseColor("#00ff00"))
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(70, builder.build());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "guardian";
String description = "alerting user";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void recognizeActivity() {
if((mActivityRecognitionClient==null)&&(!started))
{
mActivityRecognitionClient = new ActivityRecognitionClient(this);
mActivityRecognitionClient.requestActivityUpdates(0, PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
started = true;
}
speedCheckerService =this;
if(ActivityRecognitionResult.hasResult(intent))
{
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
detectedActivitiesToJson(detectedActivities);
}
}
}
I would greatly appreciate if you can help me with my problem
Use foreground service instead of normal service and do the below changes
public class SampleService extends Service {
private NotificationManager mNotificationManager;
/**
* The identifier for the notification displayed for the foreground service.
*/
private static final int NOTIFICATION_ID = 1231234;
static void startService(Context context, String message) {
Intent startIntent = new Intent(context, SampleService.class);
startIntent.putExtra("inputExtra", message);
ContextCompat.startForegroundService(context, startIntent);
}
static void stopService(Context context) {
Intent stopIntent = new Intent(context, SampleService.class);
context.stopService(stopIntent);
}
private void createNotificationChannel() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = "Sample Notification";
// Create the channel for the notification
NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name,
NotificationManager.IMPORTANCE_DEFAULT);
mChannel.setSound(null, null);
// Set the Notification Channel for the Notification Manager.
notificationManager.createNotificationChannel(mChannel);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("Service", "onCreate");
createNotificationChannel();
mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Service", "onStartCommand");
startForeground(NOTIFICATION_ID, getNotification(message);
**// This is important, When your service got killed it will try to restart //the service. But some android vendor phones are restricted this autostart**
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Service", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("Service", "onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
private Notification getNotification(String contentMessage) {
String title = getString(R.string.notification_title,
DateFormat.getDateTimeInstance().format(new Date()));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
NOTIFICATION_CHANNEL_ID).setContentTitle(title).setContentText(contentMessage)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setTicker(contentMessage)
.setAutoCancel(false)
.setWhen(System.currentTimeMillis());
return builder.build();
}
/**
* Returns true if this is a foreground service.
*
* #param context The {#link Context}.
*/
public boolean serviceIsRunningInForeground(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
Integer.MAX_VALUE)) {
if (getClass().getName().equals(service.service.getClassName())){
if (service.foreground){
return true;
}
}
}
return false;
}
}
You should use Foreground Service if you want service running even your app is in background or closed
https://androidwave.com/foreground-service-android-example/

How to stop a service at 8 pm if its running?

I have a service which captures the location of a user and updates database using retrofit. I want to stop the service automatically at 8 pm everyday if its running and also update the database that the user has punched out at 8 pm.
I want the service to start the manually but want the service to stop automatically if it is not stopped manually.
Here is my service class
public class LiveLocationService extends Service {
private static final String TAG = LiveLocationService.class.getSimpleName();
Retrofit retrofitClient;
CompositeDisposable compositeDisposable = new CompositeDisposable();
MyService myService;
String empCode, year, month, date;
FusedLocationProviderClient client;
LocationCallback locationCallback;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
retrofitClient = RetrofitClient.getInstance();
myService = retrofitClient.create(MyService.class);
empCode = intent.getStringExtra("empCode");
year = intent.getStringExtra("year");
month = intent.getStringExtra("month");
date = intent.getStringExtra("date");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onCreate() {
super.onCreate();
if (isOnline()) {
buildNotification();
requestLocationUpdates();
} else {
Log.e("MSER", "Please connect to the internet.");
}
}
private void buildNotification() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "com.deepankmehta.managementservices";
String channelName = "My Background Service";
NotificationChannel chan = null;
chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.mser)
.setContentTitle("xxxx")
.setContentText("xxxx is tracking your location.")
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_SERVICE)
.setContentIntent(intent)
.build();
startForeground(2, notification);
} else {
PendingIntent broadcastIntent = PendingIntent.getActivity(
this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
// Create the persistent notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText("xxxx is tracking your location.")
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.mser);
startForeground(1, builder.build());
}
}
private void requestLocationUpdates() {
if (isOnline()) {
LocationRequest request = new LocationRequest();
request.setInterval(10000);
request.setFastestInterval(5000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
client = LocationServices.getFusedLocationProviderClient(this);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
if (location != null) {
Log.d(TAG, "location update " + location);
double lat = location.getLatitude();
double lon = location.getLongitude();
final String time = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
compositeDisposable.add(myService.userLocation(empCode, year, month, date, time, lat, lon)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer< String >() {
#Override
public void accept(String s) throws Exception {
Log.e("data", s);
if (s.equals("\"done\"")) {
Log.e("status", "location punched");
}
}
}));
} else {
Log.d("MSER", "location update, no location found. ");
}
}
};
client.requestLocationUpdates(request, locationCallback, null);
} else {
Log.e("MSER", "Please enable location.");
}
} else {
Log.e("MSER", "Please connect to the internet.");
}
}
#Override
public void onDestroy() {
super.onDestroy();
client.removeLocationUpdates(locationCallback);
stopForeground(true);
stopSelf();
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Here is home activity class start service and stop service methods. These methods are called when the user clicks on punch in and punch out buttons respectively.
private void startTrackerService() {
final String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
final String year = date.substring(0, 4);
final String month = date.substring(5, 7);
final String dateToday = date.substring(8, 10);
Intent intent = new Intent(this, LiveLocationService.class);
intent.putExtra("empCode", empCode);
intent.putExtra("year", year);
intent.putExtra("month", month);
intent.putExtra("date", dateToday);
startService(intent);
}
private void stopTrackerService() {
stopService(new Intent(this, LiveLocationService.class));
}
You can use AlarmManager to schedule this kind of the task,
Register AlaramManger at specific time and check whether service is running, if it is running then stop service.
Here is the example of registering AlaramManager at specific time
AlarmManager alarmManager = (AlarmManager) getActivityContext()
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivityContext(), AutoStopReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivityContext(),
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
stopServieTime, pendingIntent);
Here is the Receiver Class,
public class AutoStopReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//TODO Stop service from here
}
Register receiver in AndroidMenifest.xml
<receiver android:name=".AutoStopReceiver" />

Running an Alarm Service once a day on Oreo

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.

How to send Notifications via Service

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

Categories

Resources