AlarmManager won't start service - java

I just followed the exact code in API Demo, but my service just won't start after I set the AlarmManager.
so my service is
public class CourseWatcherRefreshService extends Service {
private CourseDbAdapter mDbHelper;
private CourseWatcher watcher;
#Override
public void onCreate() {
Toast.makeText(this, "Watcher Refresh Service starts", Toast.LENGTH_SHORT).show();
mDbHelper = new CourseDbAdapter(this);
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mDbHelper.open();
Thread thread = new Thread(null, mTast, "CourseWatcherRefreshService");
thread.start();
super.onCreate();
}
#Override
public void onDestroy() {
mDbHelper.close();
super.onDestroy();
}
Runnable mTast = new Runnable() {
// some work
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Also in my AndroidManifest.xml, I put such code
<service
android:name=".CourseWatcherRefreshService"
android:process=":remote" >
</service>
And I use such code to toggle the AlarmManager
PendingIntent refreshIntent = PendingIntent.getActivity(NaviScreen.this, 0, new Intent(NaviScreen.this, CourseWatcherRefreshService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTime, 30*1000, refreshIntent);
And the code above is almost the same with the AlartService example in API Demo, but my code won't work, I can't see any sign of my service starts to work.

You are using getActivity when you should be using getService. So change the PendingIntent line to
PendingIntent refreshIntent = PendingIntent.getService(NaviScreen.this, 0, new Intent(NaviScreen.this, CourseWatcherRefreshService.class), 0);

try this :
Intent updateIntent = new Intent()
updateIntent.setClass(NaviScreen.this, CourseWatcherRefreshService.class)
PendingIntent pendingIntent = PendingIntent.getService(this, 0, updateIntent, 0);

Related

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

Notification plays on every startup

So, im working on making daily notifications for my app. And it works somehow, but the problem is that everytime i start the app or restart, it starts a notification randomly. Its just really frustating.
I've been going trough the code many times, and i just cant see why its happens
So here is everything that have to do with notifications
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public NavigationView navigationView;
private NotificationManagerCompat notificationManager;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Notifications
preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
SetNotification();
}
public void SetNotification(){
if (GetNotificationsChecked()){
Intent notificationIntent =new Intent(this,Notification_Reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
public boolean GetNotificationsChecked(){
boolean i = preferences.getBoolean("notifications", true);
return i;
}
}
Notification_reciever.java
public class Notification_Reciever extends BroadcastReceiver {
private NotificationManagerCompat notificationManagerCompat;
#Override
public void onReceive(Context context, Intent intent) {
Intent activityIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, activityIntent, 0);
notificationManagerCompat = NotificationManagerCompat.from(context);
Notification notification = new NotificationCompat.Builder(context,CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_face)
.setContentTitle("Your Daily Life Tip!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(contentIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText("Daily Notification"))
.setAutoCancel(true)
.setContentText(getlifetip(context))
.setColor(Color.parseColor("#EE3D33"))
.build();
notificationManagerCompat.notify(0, notification);
}
public String getlifetip(Context context){
//gets lifetip from jsonobject
}
MyService.java
public class MyService extends Service {
SharedPreferences preferences;
public MyService(){
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
SetNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
SetNotification();
}else Toast.makeText(this, "Intent was null", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags,startId);
}
public void SetNotification(){
preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
if (GetNotificationsChecked()){
Intent notificationIntent =new Intent(this,Notification_Reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
try{
manager.cancel(pendingIntent);
}catch (Exception ignored){}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
public boolean GetNotificationsChecked(){
boolean i = preferences.getBoolean("notifications", true);
return i;
}
}
BootReciever.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,MyService.class);
context.startService(i);
}
}
App.java
public class App extends Application {
public static final String CHANNEL_1_ID = "dailylifetip";
#Override
public void onCreate() {
super.onCreate();
CreateNotificationChannel();
}
private void CreateNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Daily Life Tips",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is the daily life tips channel");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}
Manifest
<receiver android:name=".Notification_Reciever"/>
<service android:name=".MyService" android:enabled="true" android:exported="true"/>
The user selects the hour and minute of the day in an options menu, and is saved in preferences. And then should give an notification everyday on that time. And that works!. But everytime you open the app it randomly sends you a notifications, there is no errors.

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.

Android How to keep Running the background service when app is killed by user?

I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000,
pendingIntent);
}
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("myFCMJob")
.build();
dispatcher.mustSchedule(myJob);
}
else
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
}}
I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
//setReceiver();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 0);
alarmStartTime.set(Calendar.SECOND, 5);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
//alarmStartTime.add(Calendar.DATE, 1);
}
if (alarmManager != null) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
alarmStartTime.getTimeInMillis(),
pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}
Thanks in Advance.
To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification.
It is also convenient to acquire a partial WAKE LOCK.
on your onStartCommand()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
.setContentTitle("the content title")
.setContentText("the content text")
.setSmallIcon(R.drawable.myicon)
.setOngoing(true);
// you can add other options Builder has
startForeground(1234, mBuilder.build());

How can I restart the timer, after it was cancelled?

I've got this service, which starts a timer, whenever said service also starts. The idea is that, if the user manually turns on the screen (i.e. the app. enters in the "counter" BroadcastReceiver), the timer gets cancelled. Otherwise, if the timer finishes by itself, the service will automatically stop (via onDestroy, of course).
My problem comes when I want to restart the service, WITHOUT killing the app. first. If I simply input a new number of seconds and start the service, I get the following error: java.lang.IllegalStateException: Timer was canceled
How can I get rid of said problem?
MainService:
public class MainService extends Service {
static String BROADCAST_ACTION = "com.example.vladpintea.friendsbeforecents.displayevent";
Handler handler = new Handler();
Intent intentForStars;
String usedTimer;
long interval;
TimerTask myTask = new TimerTask() { public void run() { stopSelf(); } };
Timer myTimer = new Timer();
#Override
public void onCreate() {
Toast.makeText(MainService.this, "Service, Created", Toast.LENGTH_SHORT).show();
intentForStars = new Intent(BROADCAST_ACTION);
registerReceiver(counter, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
private BroadcastReceiver counter = new BroadcastReceiver() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onReceive(Context context, Intent intent) {
myTimer.cancel();
NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent_main_activity = new Intent(context, MainActivity.class);
PendingIntent pending_intent_main_activity = PendingIntent.getActivity(context, 0,
intent_main_activity, 0);
Notification notification_popup = new Notification.Builder(context)
.setContentTitle("Friends Before Cents")
.setContentText("Oh, no! You've Lost. Try Again?")
.setSmallIcon(R.mipmap.ic_sentiment_very_dissatisfied_white_48dp)
.setContentIntent(pending_intent_main_activity)
.setAutoCancel(true)
.build();
notify_manager.notify(0, notification_popup);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(MainService.this, "Service, Started", Toast.LENGTH_SHORT).show();
try { usedTimer = intent.getStringExtra("timer"); } catch (NullPointerException ignored) {}
try { interval = Long.parseLong(usedTimer); } catch (NumberFormatException ignored) {}
myTimer.schedule(myTask, interval * 1000);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000);
return super.onStartCommand(intent, flags, startId);
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() { handler.postDelayed(this, 1000); }
};
public void addStars() { sendBroadcast(intentForStars); }
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onDestroy() {
unregisterReceiver(counter);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000);
NotificationManager notify_manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent_main_activity = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pending_intent_main_activity = PendingIntent.getActivity(this, 0,
intent_main_activity, 0);
Notification notification_popup = new Notification.Builder(this)
.setContentTitle("Friends Before Cents")
.setContentText("Congrats! You've Won Some Coins.")
.setSmallIcon(R.mipmap.ic_sentiment_very_satisfied_white_48dp)
.setContentIntent(pending_intent_main_activity)
.setAutoCancel(true)
.build();
notify_manager.notify(0, notification_popup);
addStars();
}
#Override
public IBinder onBind(Intent intent) { return null; }
You can not, the Doc reference states that once cancelled you need to create a new instance...
the Doc:
Note that calling this method from within the run method of a
repeating timer task absolutely guarantees that the timer task will
not run again.
So basically after cancel you need a new one...

Categories