i'm in a project to schedule a task with an calendar and do the job in the specific hour, the hole code is alright, working, but if i force close my app in android in the specific hour i puted in the begin of the aplication don't do my task it give me a "unfortunately TransferirLigações has stopped".
i think the timer and the AlarmManager is working, but don't do my task, give a error.
I tried ALL kinds of Scheduling task to do this, AlarmManager and Receiver, Service, IntentService, Job Scheduler and some plugins to do this, but nothing work, all give me "unfortunately TransferirLigações has stopped".
Anyone can help me? I thinks it is some errors in Manifest or Permisions, but i don't know.
Codes:
MainActivity, startAlarm class:
private void startAlarm() {
Intent intent = new Intent(getApplicationContext(), AlarmToastReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, AlarmToastReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent);
}
Receiver Class:
package com.example.usuario.tranferircalls;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmToastReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyTestService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
}
IntentService:
package com.example.usuario.tranferircalls;
import android.app.IntentService;
import android.content.Intent;
import java.util.concurrent.TimeUnit;
import static com.example.usuario.tranferircalls.MainActivity.cancelAlarm;
import static com.example.usuario.tranferircalls.MainActivity.retornarChamada;
public class MyTestService extends IntentService {
public MyTestService() {
// Used to name the worker thread
// Important only for debugging
super(MyTestService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
retornarChamada(0); //My Task, that i want to do when certain time pass.
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
retornarChamada(1);
cancelAlarm();
}
}
MyManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.usuario.tranferircalls">
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:installLocation="internalOnly"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".AlarmToastReceiver"
android:exported="true"
android:process=":remote"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<service
android:name=".MyTestService"
android:enabled="true"
android:exported="false"/>
</application>
</manifest>
Basically, thats is my app, it is 90% working, but i want to close app and it work, for have a certain that my Job / Task will work well.
grateful already, Noninus.
The Code for calculate time, it is a TimePicker that get the time, set in a static Calendar cal, and i use it to start the AlarmManager!
Calendar mcurrentTime;
mcurrentTime = Calendar.getInstance();
mcurrentTime.setTimeInMillis(System.currentTimeMillis());
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
cal.set(Calendar.HOUR_OF_DAY,selectedHour);
cal.set(Calendar.MINUTE,selectedMinute);
endTime = cal.getTime();
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Escolha a Hora para as chamadas voltarem!");
mTimePicker.show();
I would try that:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmToastReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyTestService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
}
Try this:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
am.setExactAndAllowWhileIdle(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else
am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
Related
I have read many more similar questions to this in stackoverflow but I couldn't solve my problem.
I want to trigger an android service at 3.45p.m of every day.For that I used an AlarmManager which starts the service as follows.
Application class
public class AppSettings extends Application {
#Override
public void onCreate() {
super.onCreate();
scheduleAlarm();
}
public void scheduleAlarm() {
Intent intent = new Intent(getApplicationContext(), UploadService.class);
final PendingIntent pIntent = PendingIntent.getService(this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 45);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
}
}
Service class
public class UploadService extends Service {
#Override
public void onCreate() {
Log.d("MyAlarmService", "onCreate");
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand Called", Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}
stopSelf();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("MyAlarmService", "onDestroy");
}
#Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.softarena.photosapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".app.AppSettings"
android:allowBackup="true"
android:icon="#drawable/logoo"
android:label="#string/app_name"
android:roundIcon="#drawable/logoo"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication">
<activity android:name=".views.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".views.PhotoDetailActivity" />
<activity android:name=".views.MainActivity" />
<activity android:name=".views.LoginActivity" />
<activity android:name=".views.SignUpActivity" />
<service
android:name="com.softarena.photosapp.services.UploadService"
android:enabled="true" />
</application>
</manifest>
when I run the app the my phone is onStartCommand is getting called but only when the app is open.if I close the app and wait until onStartCommand getting called it is not working.I am using a Nokia 8 device which runs android 9.I tried starting alarm manager with setAndAllowWhileIdle() and setExactAndAllowWhileIdle() also considering Doze mode but there is no way to repeat the alarm with these 2 methods and if app is closed onStartCommand not getting called.
Is this a device problem or is there anything wrong with my code?
Edit: Can I use a WorkManager or a JobScheduler to achieve my requirement?
I am trying an alarm for every fifteen minute and problem is that I hear that alarm will work when app is not running, but in my case alarm works first time and even second time if app is on screen. else not.also I want to know when first alarm is set and time was in previous time,alarm will start in recent time, but if I set pending intent for 24 hours and at that time mobile was shut down and I turned my mobile after one or two hours, will pending intent that was for a day work after 25 or 26 hours or not.please help
here is my code.
public class MainActivity extends AppCompatActivity {
Calendar calendar=Calendar.getInstance();
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.bt);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,13);
calendar.set(Calendar.MINUTE,54);
calendar.set(Calendar.SECOND,1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,13);
calendar.set(Calendar.MINUTE,54);
calendar.set(Calendar.SECOND,1);
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long time) {
calendar.setTimeInMillis(System.currentTimeMillis());
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
and here is my service
public class MyAlarm extends BroadcastReceiver{
MediaPlayer mp;
#Override
public void onReceive(Context context,Intent intent){
mp=MediaPlayer.create(context,R.raw.song);
mp.start();
}
}
manifest is here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bilal.pkr">
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.BOOT_COPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyAlarm"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
am.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
Use this.
This is my first post and I am new to Android App development so please bear with me.
I have written (and use every day) a pretty good reminders App because all the others were either too complicated or too simple. It is also on the play store, although not easy to find, but thats another story.
While I am happy with the whole App the alarms which show a notification or sound an alarm do not always happen. If the alarm is soon then it will but more than say 2 hours from now it often gets missed. Using "adb shell dumpsys alarm" it looks as if they are being discarded?
I have googled for days and have tried so many things, from this forum too, but no luck so I thought I would post some code to see if anybody can please tell me were I am going wrong as it should work as far as I can see.
So here goes.
I use alarm manager to queue the pending intent to call my broadcast receiver which starts a service which starts an activity which creates a notification and optionally sounds an alarm.
I was skipping the service bit but after googling it seems I should use a service. And as mentioned, this works fine for alarms happening soon but not after a few hours or a day or more. Could be due to Doze mode or my app being stopped by Android?
I would really appreciate some help please as I am pulling my hair out!!
Thanks in advance.
Here is my manifest. Where I think the problem is?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wingwares.reminders">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<supports-screens
android:anyDensity="true"
android:normalScreens="true" />
<application
android:icon="#drawable/reminder2"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<receiver android:name=".WidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
<service
android:name=".WidgetService"
android:exported="false"
android:permission="android.permission.BIND_REMOTEVIEWS" />
<activity
android:name=".AppPreferences" />
<activity
android:name=".ListActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RemActivity"
android:label="#string/add_reminder"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan" />
<service
android:name=".AlarmService"
android:enabled="true"
android:exported="true" >
</service>
<receiver
android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="SET_ALERT" />
</intent-filter>
</receiver>
<activity
android:name=".AlarmDialog"
android:theme="#style/AlarmDialog" />
</application>
</manifest>
And my Alarm Manager from ListActivity
public void setAlert(Context context, boolean turnOn){
intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("name", fullName());
intent.putExtra("notes", notes);
intent.putExtra("setalarm", setalarm);
intent.putExtra("millis", time.getMilliTime());
intent.putExtra("remId", remId);
pendingIntent = PendingIntent.getBroadcast(context, 8192 + remId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
if (turnOn) {
alertTime = time.getMilliTime() - (warning * 60000);
interval = getInterval();
//set repeating alarmManager just once
if (freq.equals(EVERY) && type.equals(FIXED) && date.equals(getOriginal()) && interval > 0) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, interval, pendingIntent);
} else {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, pendingIntent);
}
}
} else {
setalarm = false;
}
}
My broadcast receiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent newIntent = new Intent(context, AlarmService.class);
//pass the extras on and show the dialog
newIntent.putExtras(intent);
startWakefulService(context, newIntent);
}
}
My Service
public class AlarmService extends IntentService {
public AlarmService (){
super("AlarmService");
}
#Override
protected void onHandleIntent(Intent intent) {
Intent newIntent = new Intent(this, AlarmDialog.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
//pass the extras on and show the dialog
newIntent.putExtras(intent);
startActivity(newIntent);
AlarmReceiver.completeWakefulIntent(newIntent);
}
}
My Activity (the notification part)
public class AlarmDialog extends Activity
implements DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
Bundle extras;
int remId;
String name, notes;
Boolean setalarm;
long alarmTime;
MediaPlayer player;
PendingIntent pendingIntent;
SharedPreferences mPrefs;
NotificationManager manager;
Notification notification;
static final int SNOOZE_BUTTON = -2;
static final int DISMISS_BUTTON = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create notification and alert box if alarmManager selected
mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
extras = getIntent().getExtras();
alarmTime = extras.getLong("millis");
remId = extras.getInt("remId");
name = extras.getString("name");
notes = extras.getString("notes");
setalarm = extras.getBoolean("setalarm");
//notification first
notification = new RemNotification(this, name).get();
if (notification != null) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(remId);
manager.notify(remId, notification);
}
}
In my app I want to run some code every day at a specific time using an AlarmManager. In the android documentation I found this:
Registered alarms are retained while the device is asleep [...] but will be cleared if it is turned off and rebooted.
And that is the problem. I want to run the code even if the user reboots the phone. If the user reboots the phone he currently has to relaunch my app to start alarms again. How can I prevent this? Is there a better mechanism I should use instead?
Create Boot Receiver using following code :
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context pContext, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
// Do your work related to alarm manager
}
}
}
In your Manifest, register this Broadcast receiver :
<receiver
android:name="com.yourapp.BootBroadcastReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
And don't forget to add permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Use can u create service using broadcast reciever on device boot up
<receiver android:enabled="true" android:name=".YourReceiver"
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
You will need to add a boot receiver in your manifest like this
<application ... >
<receiver android:name=".OnBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
</intent-filter>
</receiver>
</application>
And then create the boot receiver class like this...
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctxt, Intent intent) {
AlarmHelper.setAlarm(ctxt);
}
}
My alarm helper class is a simple start of day alarm like this...
public class AlarmHelper {
public static void testAlarm(Context context) {
Calendar when = Calendar.getInstance();
when.add(Calendar.SECOND, 10);
setAlarm(context, when);
}
public static void setAlarm(Context context) {
Calendar when = Calendar.getInstance();
when.add(Calendar.DAY_OF_YEAR, 1);
when.set(Calendar.HOUR_OF_DAY, 0);
when.set(Calendar.MINUTE, 0);
when.set(Calendar.SECOND, 0);
setAlarm(context, when);
}
#SuppressLint("SimpleDateFormat")
private static void setAlarm(Context context, Calendar when) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
Boolean showNotifications = prefs.getBoolean("PREF_SHOW_NOTIFICATIONS",
false);
if (showNotifications) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), AlarmManager.INTERVAL_DAY, getPendingIntent(context.getApplicationContext()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Log.i(TAG, "Alarm set " + sdf.format(when.getTime()));
}
}
Code of Receiver:
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
BufferedReader in=new BufferedReader(
new FileReader(MainNote.log));
String AlarmString;
int i = 0;
while ((AlarmString = in.readLine())!=null)
{
Long AlarmTime = Long.parseLong(AlarmString.substring(0, AlarmString.indexOf(" ")));
if (AlarmTime < System.currentTimeMillis()) i++;
else {
String AlarmArray[] = AlarmString.split("\\s");
Intent AlarmIntent = new Intent(context, AlarmReceiver.class);
if (AlarmArray[1].equals("null")) AlarmIntent.putExtra("alarm_message", "");
else AlarmIntent.putExtra("alarm_message", AlarmArray[1]);
if (AlarmArray[2].equals("true"))
AlarmIntent.putExtra("Vibration", true);
else AlarmIntent.putExtra("Vibration", false);
if (AlarmArray[3].equals("true"))
AlarmIntent.putExtra("Sound", true);
else AlarmIntent.putExtra("Sound", false);
final int _ID = (int) System.currentTimeMillis();
PendingIntent sender = PendingIntent.getBroadcast(context , _ID, AlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, AlarmTime, sender);
}
}
Code of AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
boolean Vibration = bundle.getBoolean("Vibration");
boolean Sound = bundle.getBoolean("Sound");
if (message.equals(null))
NotifierHelper.sendNotification(context, MainNote.class, context.getResources().getString(R.string.NotTitle), context.getResources().getString(R.string.Nodiscr), 1, Sound, true, Vibration);
else
NotifierHelper.sendNotification(context, MainNote.class, context.getResources().getString(R.string.NotTitle), message, 1, Sound, true, Vibration);
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:label="#string/app_name" android:name=".MainNote">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".FingerPaint"></activity>
<receiver android:process=":remote" android:name=".AlarmReceiver"></receiver>
<receiver android:name=".OnBootReceiver">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
MainNote.log can costist for example
1304094118826 text true true
After reboot I see that my process is started, but then I dont have Notifacation. Whats wrong here? And how to debug code in OnBootReciever?
I replace my code in OnBootReciever on
Intent AlarmIntent = new Intent(context, AlarmReceiver.class);
AlarmIntent.putExtra("alarm_message", "blabla");
AlarmIntent.putExtra("Vibration", true);
AlarmIntent.putExtra("Sound", true);
final int _ID = (int) System.currentTimeMillis();
PendingIntent sender = PendingIntent.getBroadcast(context , _ID, AlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+6000, sender);
And its work. So problem in part where I read information from file.
One problem was in MainNote.log. Log its static varible so I cant contact with this here. But now I have very strange problem -
java.io.FileNotFoundException: /mnt/sdcard/AlarmsFromDrawNote.alm (Permission denied)
com.notedraw.bos.app.OnBootReceiver1.onReceive(OnBootReceiver1.java:30)
30th line is -
BufferedReader in=new BufferedReader(new FileReader(log));
WTF? (see manifest)
Your AlarmReceiver needs to be a static BroadcastReceiver like your OnBootReceiver is in order for it to act on the alarm that you set. Unfortunately, I don't think you can have more than one static receiver per application (I tried before and it did not work for me). You could try putting two intent filters on your OnBootReceiver and have it deal with both broadcasts.
In your onRecieve, simply check intent.getAction() to see which broadcast it is receiving (the boot up one or the alarm), and deal with it appropriately.
You need to create a new broadcast receiver inside the class where the broadcast will be received. Put this at the top of your class outside any methods.
AlarmReceiver intentReceiver = new AlarmReceiver ();
And you need:
#Override
protected void onPause() {
// TODO Mark time user logged out
unregisterReceiver(intentReceiver);
super.onPause();
}`
And:
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter(CustomAction.MY_INTENT);
filter.addAction(CustomAction.MY_INTENT);
registerReceiver(intentReceiver, filter);
super.onResume();
}