Cannot getApplicationContext() from BroadcastReceiver - java

My Application is asking me to create a method for getResources() or getApplicationContext().
Are these methods not allowed to be called in a BroadcastReceiver?
#Override
public void onReceive(Context context, Intent arg1) {
createNotification(Calendar.getInstance().getTimeInMillis());
}
public void createNotification(long when) {
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.stamptwo);
int smalIcon = R.drawable.stamptwoxhdpi;
Intent intent = new Intent(context.getApplicationContext(),
Lockscreen.class);
intent.putExtra(NOTIFICATION_DATA, notificationData);
intent.setData(Uri.parse("content://" + when));
PendingIntent pendingIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager notificationManager = (NotificationManager) context
.getApplicationContext().getSystemService(
Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
context.getApplicationContext())
.setWhen(when)
.setContentText(notificationContent)
.setContentTitle(notificationTitle)
.setSmallIcon(smalIcon)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setDefaults(
Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
notificationManager.notify((int) when, notification);
}
}

Another alternative to #Pankaj Kumar solution is to store the concept as a data field inside the onReceive method :
public class MyReceiver extends BroadcastReceiver {
private Context context;
#Override
public void onReceive(Context context, Intent arg1) {
this.context = context;
createNotification(Calendar.getInstance().getTimeInMillis());
}
public void createNotification(long when) {
// and use
// context.getApplicationContext()
}
 }

You will need to use context.getResources() or context.getApplicationContext() so pass the context to createNotification method.

Try this
public class NotificationAlarm extends BroadcastReceiver {
public static final String NOTIFICATION_DATA = "NOTIFICATION_DATA";
String notificationData = "";
String notificationContent = "Content";
String notificationTitle = "Title";
#Override
public void onReceive(Context context, Intent arg1) {
createNotification(context,Calendar.getInstance().getTimeInMillis());
}
public void createNotification(Context mContext,long when) {
Bitmap largeIcon = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.stamptwo);
int smalIcon = R.drawable.stamptwoxhdpi;
Intent intent = new Intent(mContext, Lockscreen.class);
intent.putExtra(NOTIFICATION_DATA, notificationData);
intent.setData(Uri.parse("content://" + when));
PendingIntent pendingIntent = PendingIntent.getActivity(
mContext, 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
mContext)
.setWhen(when)
.setContentText(notificationContent)
.setContentTitle(notificationTitle)
.setSmallIcon(smalIcon)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setDefaults(
Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
notificationManager.notify((int) when, notification);
}
}

Related

How to use JobIntentService for android +9, I want to do that listen screen if screen on app run

I try to app runs in background and service listens if screen on app launch on lock screen, we can do android 9 and 9- but we cant achieve android 9+, We use JobIntentService for android 9+ it runs sometimes how can we do that??
YourService.java extend JobIntentService
public class YourService extends JobIntentService {
public static final int JOB_ID = 1;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, YourService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.e("çalıştı","çalıştı job");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Haydi Kurtuluşa")
//.setContentText(input)
.setSmallIcon(R.drawable.more)
.setContentIntent(pendingIntent)
.setNumber(0)
.build();
Log.e("Myservice","myservice jobbbbb");
startForeground(1, notification);
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
//#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
Log.e("ekran", "açıldı");
if(intent.getAction().equals("android.intent.action.SCREEN_ON") ){
wasScreenOn = true;
Log.e("evet screen on","evet screen on");
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, i, 0);
try {
pendingIntent.send();
Log.e("pendingIntent","pendingIntent");
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
Log.e("printStackTrace","printStackTrace");
}
}
Intent startServiceIntent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
context.startForegroundService(startServiceIntent);
Log.e("Myservice","myservice receicer en alt");
}
else {
context.startService(startServiceIntent);
Log.e("Myservice","myservice receicer en dahaaaa alt");
}
YourService.enqueueWork(context, new Intent());
}
}
MyService.java
public class MyService extends Service {
MainActivity mainActivity = new MainActivity();
MyReceiver myReceiver = new MyReceiver();
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
// do your jobs here
// startForeground();
//return super.onStartCommand(intent, flags, startId);
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Haydi Kurtuluşa")
//.setContentText(input)
.setSmallIcon(R.drawable.more)
.setContentIntent(pendingIntent)
.setNumber(0) // bildirim simgesinin 1 diye gösterilip gösterilmemesini sağlar
.build();
Log.e("Myservice","myservice onstartcommand");
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
Log.e("service destroy","service destroy");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ilkk", true);
editor.commit();
super.onDestroy();
}
}
This code is in MainActivity
final Window win= getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
}
// REVEIRVER
// bu dinliyor eğer ekran açılırsa tak MyReceiver classa gönderiyor.
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
myReceiver =new MyReceiver();
registerReceiver(myReceiver,screenStateFilter);
Log.e("geldi3","geldi3");
Log.e("burada ","geldi");

Specify time delay for sending Notification in Android Studio?

I have setup Notification Channels in Android Studio for sending my notifications.
So far, I can send a notification when I click a button.
However, I want to add a delay to when the notification is sent.. for example, send the notification after 20 seconds.
I know there is a function in the AlarmManager for System.getTimeInMillis, that would be related to this, but not sure where to go from here.
Here is my code:
public class MyNotificationPublisher extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
public class EmailActivity extends AppCompatActivity {
private Button btnSend;
private NotificationManagerCompat notificationManager;
private long tenSeconds = 10000L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
notificationManager = NotificationManagerCompat.from(this);
btnSend = findViewById(R.id.button_send);
}
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
You can just schedule the notifications to be sent :-
Use the following method :
public void scheduleNotification(Context context, long delay, int notificationId)
{
//delay is after how much time(in millis) from current time you want to schedule the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(context.getString(R.string.title)) .setContentText(context.getString(R.string.content)) .setAutoCancel(true) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent intent = new Intent(context, YourActivity.class);
PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(activity); Notification notification = builder.build();
Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then, the receiver class:
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(final Context context, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(notificationId, notification);
}
}
Then, call scheduleNotification with the appropriate arguments.
Use a handler to delay the execution of notification sending code
Update your code like that
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(1, notification);
}
}, 20000);
}

How to use Broadcast receiver in non-static service class

Hello I created Broadcast Receiver in the Service class to receive application notifications but it doesn't receive any intents from Notification. When I make the broadcast receiver static, the problem is solved but at this time I cannot access the elements of the non-static upper class. I have to solve this without making it static.
My Code:
public class BackgroundService extends Service {
private final int TASK_DELAY = 0;
private final int TASK_PERIOD = 5 * 1000;
int NOTIFICATION_ID = 1;
private Context context;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static Timer timer;
private PendingIntent test;
private int runRate;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//User pressed a notifiacition button
Log.w(TAG, "onReceive: Recived" );
}
// constructor
public MyReceiver(){
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public static Timer getTimer() {
return timer;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service has been started!", Toast.LENGTH_SHORT).show();
context = getApplicationContext();
timer = new Timer();
runRate = 0;
builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("KolBoost")
.setContentText("Arkaplan servisi etkinleştirildi!")
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
Intent close = new Intent(getBaseContext(), BackgroundService.class);
close.setAction("CLOSE_SERVICE");
PendingIntent closeServiceIntent = PendingIntent.getBroadcast(getBaseContext(), 0, close, 0);
Intent i2 = new Intent(getBaseContext(), BackgroundService.class);
i2.setAction("BOOST_MEMORY");
PendingIntent boostIntent = PendingIntent.getBroadcast(getBaseContext(), 0, i2, 0);
Intent launch = new Intent(getBaseContext(),BackgroundService.class);
launch.setAction("OPEN_MANAGER");
PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0, launch, 0);
builder.setContentIntent(contentIntent);
builder.addAction(0, "Clear Memory", boostIntent);
builder.addAction(0, "Exit", closeServiceIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
test = PendingIntent.getActivity(getBaseContext(), NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
//I'm adding actions to intentFilter.
filter.addAction(close.getAction());
filter.addAction(i2.getAction());
filter.addAction(launch.getAction());
//Registering Receiver with intentFilter
registerReceiver(myReceiver,filter);
super.onCreate();
}
#Override
public void onDestroy() {
timer.cancel();
notificationManager.cancelAll();
Log.d(TAG, "onDestroy: Destroyed");
super.onDestroy();
}
}

How to make AlarmBootReceiver send notification at specified time?

I have an AlarmResiver class, it sends notifications if the user has set the time and the toggle switch is on. But this class is bad in that when the device reboots, notifications are no longer received. Then I decided to create an AlarmBootResiver class that will send notifications after the device is rebooted. Now this class is working, but it sends notifications immediately after turning on the device. How to make the AlarmBootResiver send notifications at the time set by the user in the AlarmResiver class ?
AlarmActivity code:
public class AlarmActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
private EditText mondayText;
public SwitchCompat mondaySwitch;
SharedPreferences sPref;
String timeText = "";
final String SAVED_TEXT = "saved_text";
boolean switch_On_Off;
public static final String PREFS_NAME = "Switch_On_Off_check";
final Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
mondayText = findViewById(R.id.monday_time);
mondaySwitch = findViewById(R.id.switch_monday);
// load SharedPref save text in mondayText and save switch On else Off
loadText();
loadSwitchCheck();
mondaySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (mondaySwitch.isChecked()) {
startAlarm(c);
bootStartAlarm(c);
}
saveSwitchCheck();
}
});
mondayText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
saveText();
mondaySwitch.setChecked(false);
bootStopAlarm(c);
}
private void updateTimeText(Calendar c) {
timeText = "";
timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
mondayText.setText(timeText);
}
public void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
public void bootStartAlarm(Calendar c) {
PackageManager packageManager = AlarmActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(AlarmActivity.this, AlarmBootReceiver.class);
packageManager.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
public void bootStopAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
PackageManager packageManager = AlarmActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(AlarmActivity.this, AlarmBootReceiver.class);
packageManager.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
My AlertReciever
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
}
}
My AlarmBootReciever
public class AlarmBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Objects.equals(intent.getAction(), "android.intent.action.BOOT_COMPLETED")) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
}
}
}
My Manifest file
<receiver android:name=".AlertReceiver"/>
<receiver
android:name=".AlarmBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.QUICKBOOT_POWERON" />
<uses-permission android:name="android.permission.VIBRATE" />
My NotificationHelper
public class NotificationHelper extends ContextWrapper {
public static final String channelID = "channelID";
public static final String channelName = "Channel Name";
private NotificationManager mManager;
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager() {
if (mManager == null) {
mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return mManager;
}
public NotificationCompat.Builder getChannelNotification() {
Intent resultIntent = new Intent(this, DashBoardActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("ЭЙ ТЫ!")
.setContentText("Пора на тренировку!")
.setSmallIcon(R.drawable.ic_training)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent);
}
}
You can use a BroadcastReceiver for this. This code will work, even if you restart your device or lock the device, the PowerManager does that for you. See here for more information https://developer.android.com/reference/android/os/PowerManager
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(YOUR DRAWABLE)
.setContentTitle("YOUR TITLE")
.setAutoCancel(true)
.setLights(0xFFFF0000, 500, 500)
.setColor(context.getResources().getColor(R.color.red))
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setContentText("THIS IS THE CONTENT OF THE NOTIFICATION");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
#SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mNotificationId is a unique integer your app uses to identify the
// notification. For example, to cancel the notification, you can pass its ID
// number to NotificationManager.cancel().
mNotificationManager.notify(0, mBuilder.build());
}
}
You can trigger AlarmReceiver using this in MainActivity for example where you can set your time of trigger, see comment.
public void doNotification() {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// InexactRepeating allows Android to optimize the energy consumption //ms, s, min
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24 * 30, pending); //every month
}

How to send notification with background service in Android Studio?

I want to send push notifications in my app but after few minutes android kill my background service and notifications not showing. How to make background service which android will not close?
BackroundService.class
public Context context = this;
public android.os.Handler handler = new Handler();
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.e("Service", "Service crated!");
runnable = new Runnable() {
public void run() {
Log.e("Service", "Service is still running!");
Toast.makeText(context, "Service is still running", Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable, 50000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Log.e("Service", "Service started by user!");
}
AlarmReceiver.class
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("ID", 0);
String message = intent.getStringExtra("TEXT");
String tittle = intent.getStringExtra("TITTLE");
Intent mainIntent = new Intent(context, BackgroundService.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.drawable.finance43)
.setContentTitle(tittle)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_MESSAGE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "REMINDERS";
NotificationChannel channel = new NotificationChannel(channelId,
"Reminder",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
notificationManager.notify(notificationId, builder.build());
}
When I start app i see "Service is still running!" for about 1 hour.

Categories