I'm developing an app. In it user can input his friend's information - name and date of birth. When information is added, a service should start which should count how much time left and send a notification, when friend is having a birthday soon. Service takes info from database. When I add information, service just crashes. Here's my service code
Timer timer = new Timer();
DB2 db;
Cursor cursor;
Calendar x = Calendar.getInstance();
int y = x.get(Calendar.YEAR);
int m = x.get(Calendar.MONTH) + 1;
int d = x.get(Calendar.DAY_OF_MONTH);
int h = x.get(Calendar.HOUR_OF_DAY);
int min = x.get(Calendar.MINUTE);
int s = x.get(Calendar.SECOND);
Handler handler;
NotificationManager nm;
int l, p, a, i, month, hours, minutes, seconds, m22, d22, v, g, t;
int[] k = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class UpdateTimeTask extends TimerTask{
public void run(){
MS2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
db.open();
cursor = db.getAllData();
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
int d110 = cursor.getInt(cursor.getColumnIndex("day")); //here it should do some manipulations with every item in DB.
}
while (cursor.moveToNext());//takes next item
}
}
});
cursor.close();
}
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
public void onCreate() {
super.onCreate();
handler = new Handler();
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//db = new DB2(this);
//db.open();
}
public void not() {
Intent resultIntent = new Intent(this, TEST2.class);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
db = new DB2(this);
db.open();
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
timer.schedule(new UpdateTimeTask(), 0, 1000);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
When I have my code like this
class UpdateTimeTask extends TimerTask{
public void run(){
db.open();
cursor = db.getAllData();
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
int d110 = cursor.getInt(cursor.getColumnIndex("day")); //here it should do some manipulations with every item in DB.
}
while (cursor.moveToNext());//takes next item
}
cursor.close();
}
}
There's no crash. Just no notification
Related
I have been trying to implement a way that the application detect wake word like "Hey google" or "Jarvis". I did some research and found out porcupine helps towards solving the wake word problem but now the problem is I can't seem to trigger startRecognition() to listen again for the user input and then carry forward with it. I still tried to trigger startRecognition() but then it was asking me to do speechRecognizer.Destroy() which I tried doing with the porcupine onDestroy method but then it just stopped working. Sorry if I confused anyone, I will attach my code I will really appreciate everyone's help as I have been trying to solve this problem for a while now.
Another question is what does the following line of code do?
PendingIntent contentIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class), // this line ?
0);
The code currently :(
public class PorcupineService extends Service {
private static final int REQUEST_RECORD_AUDIO_PERMISSION_CODE = 1;
private SpeechRecognizer speechRecognizer;
TextToSpeech textToSpeech;
String userResponse;
Float speechRate = 2f;
private static final String CHANNEL_ID = "PorcupineServiceChannel";
private PorcupineManager porcupineManager;
private int numUtterances;
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID,
"Porcupine",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class),
0);
numUtterances = 0;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Wake word")
.setContentText("Service running")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1234, notification);
try {
porcupineManager = new PorcupineManager.Builder()
.setKeyword(Porcupine.BuiltInKeyword.JARVIS)
.setSensitivity(0.7f).build(
getApplicationContext(),
(keywordIndex) -> {
Log.i("YOU SAID IT!", "yesss");
textSpeechInitialize();
startRecognition();
listening();
numUtterances++;
PendingIntent contentIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class),
0);
final String contentText = numUtterances == 1 ? " time!" : " times!";
Notification n = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Wake word")
.setContentText("Detected " + numUtterances + contentText)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1234, n);
});
porcupineManager.start();
} catch (PorcupineException e) {
Log.e("PORCUPINE", e.toString());
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
try {
porcupineManager.stop();
porcupineManager.delete();
speechRecognizer.destroy();
} catch (PorcupineException e) {
Log.e("PORCUPINE", e.toString());
}
super.onDestroy();
}
public void listening(){
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {}
#Override
public void onRmsChanged(float rmsdB) {}
#Override
public void onBufferReceived(byte[] buffer) {}
#Override
public void onEndOfSpeech() {}
#Override
public void onError(int error) {
String errorMessage = getErrorText(error);
Log.i(">>> INFO", "Failed " + errorMessage);
}
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
userResponse = matches.get(0);
userResponse = userResponse.toLowerCase();
toSpeak(userResponse);
}
#Override
public void onPartialResults(Bundle partialResults) {}
#Override
public void onEvent(int eventType, Bundle params) {}
});
}
public void textSpeechInitialize(){
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
textToSpeech.setLanguage(Locale.getDefault());
textToSpeech.setSpeechRate(speechRate);
String greet = greetings();
toSpeak(greet);
startRecognition();
} else {
Toast.makeText(getApplicationContext(), "Feature not supported", Toast.LENGTH_SHORT).show();
}
}
});
}
public String getErrorText(int errorCode) {
String message;
switch (errorCode) {
...
}
return message;
}
public static String greetings(){
String s = "";
Calendar c = Calendar.getInstance();
int time = c.get(Calendar.HOUR_OF_DAY);
if (time >= 0 && time < 12){
s = "Good Morning sir! how can I help you today?";
} else if (time >= 12 && time < 16){
s = "Good Afternoon sir";
} else if (time >= 16 && time < 22){
s = "Good Evening sir";
}
else if (time >= 22 && time < 24){
s = "Hello sir, you need to take some rest... its getting late!";
}
return s;
}
private void startRecognition() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en");
speechRecognizer.startListening(intent);
}
private void toSpeak(String toSpeak){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.i(">>>Voice Info", String.valueOf(textToSpeech.getVoice()));
}
try {
textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
} catch (Exception e){
e.printStackTrace();
}
}
}
Since startRecognition() is not getting triggered, check permission to record audio in MainActivity. Your app's AndroidManifest.xml should have the following line:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
or, you might have to explicitly ask for user permission. You can refer to this article on Medium:
https://medium.com/picovoice/no-way-google-build-your-own-wake-word-service-on-android-339a0189ff4c
Intents are objects of android.content.Intent type. It's basically a passive data structure holding an abstract description of an action to be performed(like starting activities or services). Here, it starts MainActivity class, which gets triggered immediately after the user logs in to mobile SDK apps.
new Intent(this, MainActivity.class)
For more details, you can check out the following docs:
https://developer.android.com/reference/android/app/PendingIntent#getActivity(android.content.Context,%20int,%20android.content.Intent,%20int)
https://developer.android.com/reference/android/content/Intent
https://www.vogella.com/tutorials/AndroidIntent/article.html
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();
}
}
I have an app that records the time of the job, i mean that calculates the job time for that purpose i used chronometer to run the time. Since the job is 9 hours long so user can't open the app for that long. For that purpose i am using the Service which indicate the time. Since i cannot use Chronometer because
Chronometer is a UI widget (actually a TextView) in Android. So, i can't use it for non-UI purposes. So i have to use timer to do the job. But i do not know how can i achieve this. Any code or help is appreciated. Thanks
When i hit the start button the chronometer starts like this
and my service also started but i get the time as 00:00:00 like this
i just want that timer should run in the service and i can see the time in service and i do not want to deal or use the time that is running in service, the time in service will show user that how much time they spend on job.
Service Class
public class ServiceTimer extends Service {
// Chronometer chronometer ;
//String valueOfTime ;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
// chronometer = new Chronometer(this);
//chronometer.setText("00:00:00");
//chronometer.setOnChronometerTickListener(new //Chronometer.OnChronometerTickListener() {
// #Override
// public void onChronometerTick(Chronometer chronometer) {
// CharSequence text = chronometer.getText();
// if (text.length() == 5) {
// chronometer.setText("00:"+text);
// } else if (text.length() == 7) {
// chronometer.setText("0"+text);
// }
//}
// });
// chronometer.start();
//before i know about chronometer that i cannot use it in service
// this is what i have so for with chronometer to achieve
// but failed ...
Intent notificationIntent = new Intent(this, Timer_FullTime.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(chronometer.getText().toString())
.setSmallIcon(R.mipmap.logoback)
.setContentText(input)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
UPDATE this is how i get what i wanted or asked in the question
public class ServiceTimer extends Service {
private int THE_ID_TO_UPDATE = 1;
private static Timer timer = new Timer();
private Context ctx;
private int second = 0 ;
NotificationManager notificationManager ;
private int minute = 0 ;
private int hour = 0 ;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
NotificationCompat.Builder notification ;
#Override
public void onCreate() {
super.onCreate();
super.onCreate();
ctx = this;
}
private class mainTask extends TimerTask
{
public void run()
{
second = second + 1 ;
if (second == 60){
minute++ ;
second = 0 ;
}
if (minute == 60){
hour++;
minute = 0 ;
second = 0 ;
}
notification.setContentText( hour + "h " + minute + "m " + second+"s");
notificationManager.notify(THE_ID_TO_UPDATE , notification.build());
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, Timer_FullTime.class) ;
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0) ;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new NotificationCompat.Builder(this, CHANNEL_ID);
notification.setContentTitle(input);
notification.setSmallIcon(R.mipmap.logoback);
notification.setOnlyAlertOnce(true);
notification.setWhen(System.currentTimeMillis());
notification.setContentIntent(pendingIntent);
notification.setLights(Color.RED, 1000, 1000);
notification.setVibrate(new long[]{0, 400, 250, 400});
notification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
notification.build();
notificationManager.notify(THE_ID_TO_UPDATE , notification.build());
startForeground(THE_ID_TO_UPDATE, notification.build());
timer.scheduleAtFixedRate(new mainTask(), 0, 1000);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
You could try to use a Timer with a TimerTask:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Update your counter/notification each second
}
}, 0, 1000);
Link to official documentation: https://developer.android.com/reference/java/util/Timer
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...
I'm trying to start a service scheduled for a specific date. My problem is that the intent which should start the service, doesn't do it.
This is my Helper which should start the service
public class AlarmHelper {
public static void createAlarm(Context ctx, TRANSAZIONE_MENSILE tm) {
int giorniDifferenza = calcolaGiorni(tm.getMonthDay());
int secondiDifferenza = calcolaSecondi();
int minutiDifferenza = calcolaMinuti();
int oreDifferenza = calcolaOre();
Intent alarmIntent = new Intent(ctx, AlarmService.class);
alarmIntent.putExtra("secondi", secondiDifferenza);
alarmIntent.putExtra("minuti", minutiDifferenza);
alarmIntent.putExtra("ore", oreDifferenza);
alarmIntent.putExtra("giorni", giorniDifferenza);
alarmIntent.putExtra("requestCode", tm.getRequestCode());
ctx.startService(alarmIntent);
}
//other methods not relevant in the process
}
And here is the AlarmService
public class AlarmService extends Service {
Alarm alarm = new Alarm();
public void onCreate(){
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Bundle extras = intent.getExtras();
int sec = extras.getInt("secondi");
int min = extras.getInt("minuti");
int hour = extras.getInt("ore");
int days = extras.getInt("giorni");
int requestCode = extras.getInt("requestCode");
alarm.setAlarm(this, sec, min, hour, days, requestCode);
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
And finally this is the BroadcastReceiver
public class Alarm extends BroadcastReceiver {
private static final int SECS = 1000;
private static final int MINS = 60000;
private static final int HOURS = 3600000;
private static final int DAYS = 86400000;
#Override
public void onReceive(Context ctx, Intent intent) {
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//qui metto il codice
//todo codice
//prendo il request code
int requestCode = intent.getIntExtra("requestCode", -1);
if (requestCode != -1) {
// cancello l'allarme che si sa mai
cancelAlarm(ctx, requestCode);
// ora bisogna anche che la transazione sia salvata
AlarmHelper.resolveAlarm(ctx, requestCode);
// ora ricreo l'allarme nuovo per il mese prossimo
AlarmHelper.restartAlarm(ctx, requestCode);
}
wl.release();
}
public void setAlarm(Context ctx, int sec, int min, int hours, int days, int requestCode) {
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctx, Alarm.class);
i.putExtra("requestCode", requestCode);
PendingIntent pi = PendingIntent.getBroadcast(ctx, requestCode, i, 0);
int tempoInMilli = 0;
tempoInMilli += (SECS * sec);
tempoInMilli += (MINS * min);
tempoInMilli += (HOURS * hours);
tempoInMilli += (DAYS * days);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tempoInMilli, pi);
}
public void cancelAlarm(Context context, int requestCode) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
The Intent simply doesn't reach the service, how should I fix it? Any help will be appreciated