A push notification set up using alarm manager and pending intent is displaying unusual behavior. For some reason, the notification comes up a minute or less after I open up the app. Sometimes more than once a minute, then it doesn't show up for a while. My idea is to have the notification be given off once a day, assuming the user hasn't access my app in over 24hrs. I intend to cancel any previous timer, and start a new one for 1 day when the user next accesses my app. Below is my code.
public class Main_Menu extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Button goToGame1;
goToGame1 = (Button) findViewById(R.id.Game1);
goToGame1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent beAtGame1 = new Intent(Main_Menu.this, memory_modes.class);
startActivity(beAtGame1);
}
});
Button goToGame2;
goToGame2 = (Button) findViewById(R.id.Game2);
goToGame2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent beAtGame2 = new Intent(Main_Menu.this, computation_modes.class);
startActivity(beAtGame2);
}
});
Button goToGame3;
goToGame3 = (Button) findViewById(R.id.Game3);
goToGame3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent beAtGame3 = new Intent(Main_Menu.this, evaluation_modes.class);
startActivity(beAtGame3);
}
});
Button goToGame4;
goToGame4 = (Button) findViewById(R.id.Game4);
goToGame4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent beAtGame4 = new Intent(Main_Menu.this, attention_modes.class);
startActivity(beAtGame4);
}
});
Button goToTrackers;
goToTrackers = (Button) findViewById(R.id.Trackers);
goToTrackers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent beAtTrackers = new Intent(Main_Menu.this,trackerMenu.class);
startActivity(beAtTrackers);
}
});
Intent intent = new Intent(Main_Menu.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Main_Menu.this, 1, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(alarm.RTC_WAKEUP, System.currentTimeMillis(), alarm.INTERVAL_DAY, pendingIntent);
}
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
and
public class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
public void showNotification(Context context) {
Intent intent = new Intent(context, Main_Menu.class);
PendingIntent pi = PendingIntent.getActivity(context, 1, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.smalliconfinal)
.setColor(Color.argb(000,255,177,17))
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon4))
.setContentTitle("Title")
.setContentText("Some text.");
mBuilder.setLights(0xffffb111, 750, 750);
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
and from my Manifest:
<receiver android:name=".Receiver"></receiver>
Anyone know why this issue occurs?
Much appreciated,
thank you.
The second parameter to the AlarmManager.setRepeating method is the time the alarm should first go off.
You're calling this method using these parameters:
alarm.setRepeating(alarm.RTC_WAKEUP, System.currentTimeMillis(), alarm.INTERVAL_DAY, pendingIntent);
Which means that you're setting the repeating alarm to go off as soon as you call the method (when the Main_Menu activity is created).
From your description it seems like you're looking for something like this:
alarm.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + AlarmManager.INTERVAL_DAY), AlarmManager.INTERVAL_DAY, pendingIntent);
Related
I'm trying 1 month now to make a feature witch sends to the user one notification daily at the time the user has selected but when the onTimeSet() called i'm getting only this error below and the Notification is not coming to the user
I try these solutions below:
removing all code from onTimeSet() & startAlarm() inside my activity
changing this to SetNotificationActivity.this
Invalidate chaches / restart
Error:
E/InputDispatcher: Window handle Window{838da5a u0 com.george.igrow/com.george.igrow.SetNotificationActivity} has no registered input channel
SetNotificationActivity.java:
public class SetNotificationActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notification);
final Button setAlarm = findViewById(R.id.buttonAlarm);
final Button skip_btn = findViewById(R.id.button4);
setAlarm.setOnClickListener(v -> {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
});
skip_btn.setOnClickListener(v -> {
finish();
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
startAlarm(c);
}
private 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.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
}
}
AlertReceiver.java:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SplashScreenActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Send notification for the current Alarm
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
//nb.setContentIntent(pendingIntent);
notificationHelper.getManager().notify(1, nb.build());
}
}
In my app, there is a login activity first and a home activity. After logging in using volley and passing parameters to home activity in an intent, I'm able to start a foreground service that keeps the app running in background with notifications and getting back to home activity by clicking on the notification with the help of pending intent.
Now, I'm searching for how to open the app from main menu and accessing directly home activity with the pending intent of the foreground service. Maybe should I pass the parameters of the pending intent to the login activity and check them to redirect to home activity, but i'am stuck with this and don't understand.
Here is the login activity Page :
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.signIn);
// Login On Button Click
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();}
});
// THIS IS THE SOLUTION THAT I THOUGHT ABOUT : if the intent is not null open HomeActivity
Intent startinIntent = getIntent();
if (startinIntent.getStringExtra("userLogged") != null && !startinIntent.getStringExtra("userLogged").isEmpty()) {
String userLogged = startinIntent.getStringExtra("userLogged");
Intent startAgain = new Intent(this, HomeActivity.class);
tackBackWork.putExtra("userLogged", userLogged);
startActivity(startAgain);
Log.d("this is the ilue", userLogged);
}
}
private void login(){
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
try {
//input your API parameters
object.put("u",username.getText());
object.put("p",password.getText());
} catch (JSONException e) {
e.printStackTrace();
}
// Enter the correct url for your api service site
String url = getResources().getString(R.string.loginUrl);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String msg = response.getString("msg");
if(msg.contains("true")){
Intent loggedIn = new Intent(LoginActivity.this, HomeActivity.class);
loggedIn.putExtra("userLogged", response.toString());
startActivity(loggedIn);
finish();
}else{
Toast.makeText(getApplicationContext(), "Identifiants Incorrectes", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e){
Toast.makeText(getApplicationContext(), "erreur - 200 ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Volley on error listener", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
Here is the Home activity
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String userLogged = getIntent().getStringExtra("userLogged");
}
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
public void onResume(){
super.onResume();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onPause() {
super.onPause();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
}
Here is foreground Service Page :
public class ForegroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
String userLogged = intent.getStringExtra("userLogged");
Intent backToHomeActivity = new Intent(this, HomeActivity.class);
backToHomeActivity.putExtra("userLogged", userLogged);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, backToHomeActivity, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
// .setLargeIcon()
// .setColor()
.setContentIntent(pendingIntent)
.setContentText(input)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm new to all of this. please help me.
The solution is to use SharedPreferences.
public class LoginActivity extends AppCompatActivity {
Button login;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.loginBtn);
sp = getSharedPreferences("login",MODE_PRIVATE);
if(sp.getBoolean("logged",false)){
goToMainActivity();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToMainActivity();
sp.edit().putBoolean("logged",true).apply();
}
});
}
public void goToMainActivity(){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
See the Tutorial below
https://medium.com/#prakharsrivastava_219/keep-the-user-logged-in-android-app-5fb6ce29ed65
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.
I'm trying to make my app issue a notification at a specific time(using timePicker) and repeat it daily(using setRepeat method).
Everything is working fine until I cancel the alarm to check if cancellation works or not. But after canceling the alarm if I set the alarm again to issue a notification, it just doesn't work unless my app is running.
I've turned an activity into a dialog and starting with startActivityForResult, getting time setting on the calendar which alarm manager uses. Thanks in advance.
NotificationCenter.class (java file of the activity cum dialog):
// IMPLEMENTATION OF TIME PICKER'S TIME CHANGE EVENT
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
savedHour = hourOfDay;
savedMinute = minute;
}
});
// IMPLEMENTATION OF SAVE BUTTON
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//using this for couple of reasones
Boolean isNotification = notificationSwitch.isChecked();
editor.putBoolean("isNotification", isNotification);
editor.putInt("saved_hour", savedHour);
editor.putInt("saved_minute", savedMinute);
editor.putBoolean("hasTimeSaved", true);
editor.apply();
//sending this intent to mainActivity as a result
Intent result = new Intent();
result.putExtra("saved_hour", savedHour);
result.putExtra("saved_minute", savedMinute);
setResult(2, result);
finish();
}
});
MainActivity.xml
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To remove status bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
// ALARM SERVICE FOR NOTIFICATION
alarmService = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar = Calendar.getInstance();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
alertIntent = new Intent(this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// GET THE NOTIFICATION LINEAR LAYOUT AND SET AN ON CLICK LISTENER TO IT
LinearLayout notificationManager = (LinearLayout) findViewById(R.id.notification_manager);
notificationManager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(getApplicationContext(), NotificationCenter.class), 11);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 11) {
Toast.makeText(this,"request_code_ok", Toast.LENGTH_SHORT).show();
if (resultCode == 2) {
Toast.makeText(this,"result_code_ok", Toast.LENGTH_SHORT).show();
if (preferences.getBoolean("isNotification", false)) {
Toast.makeText(this, "true", Toast.LENGTH_SHORT).show();
int savedHour = data.getIntExtra("saved_hour", 0);
int savedMinute = data.getIntExtra("saved_minute", 0);
calendar.set(Calendar.HOUR_OF_DAY, savedHour);
calendar.set(Calendar.MINUTE, savedMinute);
calendar.set(Calendar.SECOND, 1);
Intent alertIntent = new Intent(this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmService.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
} else {
alarmService.cancel(pendingIntent);
Toast.makeText(this,"alarm_cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}
MyBroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// NOTIFICATION
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setTicker("Alert!")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, ChapterOne.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ChapterOne.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setPriority(2);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify( 0,mBuilder.build());
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="false"/>
<service android:name=".NotificationService" android:enabled="true" android:exported="false"/>
I want to start an Intent with an AlarmManager referring to code in an inner class.
My code in MainActivity.class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
[...]
DataProcessing2 dp = new DataProcessing2();
startstop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
if(!listening){
Log.i("Start","Button Pressed");
listening = true;
startstop.setText(R.string.stop);
dp.start(getApplicationContext());
}
}
});
}
}
My code in the DataProcessing2.class
public class DataProcessing2 {
public void start_accel(Context context){
Log.i("Start Accel","Accessed");
accel.setAccel(context);
accel.listenAccel();
Intent getAccelValuesIntent = new Intent(context, DataProcessing2.GetAccelValues.class);
PendingIntent getValues = PendingIntent.getService(context, 0, getAccelValuesIntent, 0);
getAccelData = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
getAccelData.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), sampling_acc_ms, getValues);
}
public class GetAccelValues extends IntentService {
public GetAccelValues() {
super("GetAccelValues");
}
[...]
#Override
protected void onHandleIntent(Intent intent) {
Log.i("Acc Values","Intent received");
accel.calculateAccelerometerData();
getCalculatedData();
boolean moving = sD.acc_delta > sD.acc_th;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(NOTIFICATION_SERVICE);
broadcastIntent.putExtra("name", "answerAccelerometer");
broadcastIntent.putExtra("moving", moving);
sendBroadcast(broadcastIntent);
}
}
The problem is that I never get the receive the Intent on GetAccelValues.
The problem is that you're using incompatible clocks. You should either use AlarmManager.ELAPSED_REALTIME_WAKEUP together with System.elapsedRealtime(), or AlarmManager.RTC_WAKEUP together with System.currentTimeMillis(). For example:
getAccelData.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), sampling_acc_ms, getValues);