I am new to alarm functionality. I am developing a application of alarm. In which i am able to set the alarm. And when the alarm rings the customize note comes on the pop up window.
My code is :
Main.java
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class AlarmMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.DAY_OF_MONTH, 31);
cal.set(Calendar.HOUR_OF_DAY, 17);
cal.set(Calendar.MINUTE, 40);
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, AlarmReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent);
finish();
}
}
AlarmRecieverActivity.java
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
public class AlarmReceiverActivity extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
callStop();
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
private void callStop(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Medicine Alert");
alertDialogBuilder.setMessage("ABC");
alertDialogBuilder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mMediaPlayer.stop();
finish();
} //end onClick.
}); // end alertDialog.setButton.
alertDialogBuilder.show();
}
}
And the requirement is that: Now i want to set multiple alarms.
The alarm should set for the next 5 to 6 days as the parameter passed.
User can edit alarm, delete alarm and delete all alarms at once.
What changes should i do in code and what should i add more. Please suggest.
Thank you.
Take a look at AlarmManager.setRepeating.
Related
I'm developing android application using local notifications. I was implemented local notifications using Services. In services local notifications work but when I kill the app the service destroyed. Notifications not working. Now I want to implement local notifications using alarm manager how can I do this with alarm manager
Here is Service Class.
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.deemsysinc.cyberhealthapp.R;
import com.deemsysinc.cyberhealthapp.weightgoal.WeightGoalActivity;
import com.google.gson.Gson;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
public class NotificationService extends Service{
private IBinder iBinder=new MyBinder();
SharedPreferences prefs;
SharedPreferences.Editor editor;
Handler handler;
// timer handling
NotificationManager manager;
Notification myNotication;
static TimerTask timerTask;
Date date1;
Date date2;
ArrayList<NotificationList> notificationLists;
int temp=0;
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
return true;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
handler=new Handler();
prefs = getSharedPreferences(configuration.AppPrefernce, MODE_PRIVATE);
editor = prefs.edit();
notificationLists=new ArrayList<NotificationList>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timerStart();
//Remove();
return Service.START_STICKY;
}
public void showNotifications()
{
Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("hh:mm a");
String localTime = date.format(currentLocalTime);
String converted = localTime.replace("am", "AM").replace("pm", "PM");
Toast.makeText(getApplicationContext(),"Timer Running",Toast.LENGTH_LONG).show();
Log.d("Locals",""+local);
//Toast.makeText(getApplicationContext(),"Service Checked",Toast.LENGTH_SHORT).show();
if(!prefs.getString("weight_hr","").equals("")) {
if (prefs.getString("weight_hr", "").equals(converted)) {
temp++;
Bundle bundle=new Bundle();
//SimpleDateFormat writeformat = new SimpleDateFormat("dd/MM/yyyy");
//String formattedDate = writeformat.format(calendar.getTime());
if(temp==1) {
notificationLists.add(new NotificationList("Weight", "It's time to log your weight today. Click to update weight!", ""));
Gson gson = new Gson();
String json = gson.toJson(notificationLists);
editor.putString("notificationlist", json);
editor.commit();
bundle.putString("fromNotificationCenter","1");
}
else
{
bundle.putString("fromNotificationCenter","0");
}
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(), WeightGoalActivity.class);
notificationIntent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 6, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setAutoCancel(true);
builder.setContentTitle("Cyberhealths");
builder.setContentText("It's time to log your weight today. Click to update weight!");
builder.setSmallIcon(R.drawable.my_icon);
builder.setContentIntent(pendingIntent);
builder.setOngoing(false);
manager.notify(6, builder.build());
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(6);
Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show();
}
private void timerStart() {
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
showNotifications();
} catch (Exception e) {
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 0, 65000);
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
public class MyBinder extends Binder {
public NotificationService getService() {
return NotificationService.this;
}
}
}
From the documentation of startForeground():
Make this service run in the foreground, supplying the ongoing
notification to be shown to the user while in this state. By default
services are background, meaning that if the system needs to kill them
to reclaim more memory (such as to display a large page in a web
browser), they can be killed without too much harm. You can set this
flag if killing your service would be disruptive to the user, such as
if your service is performing background music playback, so the user
would notice if their music stopped playing.
In your showNotification() method you need to start service on foreground upon Notification,
int FOREGROUND_ID = 6;
....
builder.setOngoing(false);
Notification notification = builder.build();
manager.notify(FOREGROUND_ID, notification);
startForeground(FOREGROUND_ID, notification);
Once you need to stop the service, simply call:
stopForeground(**false / true**);
Pass false if you don't want Notification to be removed once service stops, or true if you want that Notification should be removed automatically.
Here i have a code to set the date and time by the user.When the time arrives the notification will pop up.
The problem is that the user have to set the time manually.I want to set it programatically to a specific date, lets say 23 January 2016.So that the user have to just click the set button and forget about other things.
java file of the AlarmReceiiver:-
package com.defcomdevs.invento16;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
int notifyId=1;
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"Alarm has been set",Toast.LENGTH_SHORT).show();
/*Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();*/
NotificationCompat.Builder mNotify=new NotificationCompat.Builder(context);
mNotify.setSmallIcon(R.drawable.index);
mNotify.setContentTitle("Coding");
mNotify.setContentText("INVENTO: Coding competition is going to be conducted today.");
Intent resultIntent=new Intent(context,Coding.class);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(context);
stackBuilder.addParentStack(Coding.class); //add the to-be-displayed activity to the top of stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mNotify.setContentIntent(resultPendingIntent);
NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifyId,mNotify.build());
}
}
AlarmActivity.java :-
package com.defcomdevs.invento16;
import android.os.Bundle;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class AlarmActivity extends AppCompatActivity {
private TextView t1,t2,info;
private DatePicker dp;
private TimePicker tp;
private View v1,v2;
private Button b1;
final static int req1=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
b1= (Button) findViewById(R.id.submitalarm);
t1= (TextView) findViewById(R.id.setdate);
t2= (TextView) findViewById(R.id.settime);
tp= (TimePicker) findViewById(R.id.timePicker);
info= (TextView) findViewById(R.id.alarminfo);
dp= (DatePicker) findViewById(R.id.datepicker);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
Calendar now=Calendar.getInstance(); //initialize calendar variable
dp.init(
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH),
null
); //read current day,month & year
//now is a variable,it doesn't mean 'now'
tp.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); //set current hour
tp.setCurrentMinute(now.get(Calendar.MINUTE)); //set current minute
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar current = Calendar.getInstance(); //initialize an instance of Calendar
Calendar cal = Calendar.getInstance();
cal.set(dp.getYear(),
dp.getMonth(),
dp.getDayOfMonth(),
tp.getCurrentHour(),
tp.getCurrentMinute(),
00); //get current time and date
if (cal.compareTo(current) <= 0) {
Toast.makeText(getApplicationContext(),"Invalid Date/Time.Please Re-enter",Toast.LENGTH_LONG).show();
}
else{
setAlarm(cal);
}
}
});
}
private void setAlarm(Calendar target){
info.setText("\n\n***\n"
+ "Alarm is set# " + target.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), req1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, target.getTimeInMillis(), pendingIntent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id==android.R.id.home){
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
How could i do this?please help.Thanks.
This code will set the alarm to 23 January, 2016, 18:05:00. So you don't need TimePicker and DatePicker. See doc here: Calendar
Calendar cal = Calendar.getInstance();
cal.set(2016, 0, 23, 18, 5, 0);
setAlarm(cal);
here is my contribution what i did i haven't tested this but the concept is correct just try it out ...
Calendar calendar = Calendar.getInstance();
calendar.set(2016,MonthSelect("May"),DaySelect("Monday"));
if (SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}else if (Build.VERSION_CODES.KITKAT <= SDK_INT && SDK_INT < Build.VERSION_CODES.M) {
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
else if (SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
.......... then the other functions called..
private int MonthSelect(String mMonth){
if(mMonth=="January"){
return 0;
}else if(mMonth.equalsIgnoreCase("February")){
return 1;
}else if(mMonth.equalsIgnoreCase("March")){
return 2;
}else if(mMonth.equalsIgnoreCase("April")){
return 3;
}else if(mMonth.equalsIgnoreCase("May")){
return 4;
}else if(mMonth.equalsIgnoreCase("June")){
return 5;
}else if(mMonth.equalsIgnoreCase("July")){
return 6;
}else if(mMonth.equalsIgnoreCase("August")){
return 7;
}else if(mMonth.equalsIgnoreCase("September")){
return 8;
}else if(mMonth.equalsIgnoreCase("October")){
return 9;
}else if(mMonth.equalsIgnoreCase("Novermber")){
return 10;
}else {
return 11;
}
}
private int DaySelect(String mDay){
if(mDay.equalsIgnoreCase("Monday")){
return Calendar.MONDAY;
}else if (mDay.equalsIgnoreCase("Tuesday")){
return Calendar.TUESDAY;
}else if (mDay.equalsIgnoreCase("Wednesday")){
return Calendar.WEDNESDAY;
}else if (mDay.equalsIgnoreCase("Thursday")){
return Calendar.THURSDAY;
}else if (mDay.equalsIgnoreCase("Friday")){
return Calendar.FRIDAY;
}else if (mDay.equalsIgnoreCase("Saturday")){
return Calendar.SATURDAY;
}else{
return Calendar.SUNDAY;
}
}
I want to fire a local notification every 24 hours at a specific time say evening 6 o clock
i have refered this code
here
and
here
This is the code i am trying
package com.banane.alarm;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
Button bananaButton;
TextView notificationCount;
TextView notificationCountLabel;
int mNotificationCount;
static final String NOTIFICATION_COUNT = "notificationCount";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// Restore value of members from saved state
mNotificationCount = savedInstanceState.getInt(NOTIFICATION_COUNT);
}
setContentView(R.layout.activity_main);
bananaButton = (Button)findViewById(R.id.bananaButton);
notificationCount = (TextView)findViewById(R.id.notificationCount);
notificationCountLabel = (TextView)findViewById(R.id.notificationCountLabel);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(NOTIFICATION_COUNT, mNotificationCount);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onNewIntent( Intent intent ) {
Log.i( TAG, "onNewIntent(), intent = " + intent );
if (intent.getExtras() != null)
{
Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
}
super.onNewIntent( intent );
setIntent( intent );
}
public void triggerAlarm(View v){
setAlarm();
bananaButton.setVisibility(View.GONE);
notificationCountLabel.setVisibility(View.VISIBLE);
notificationCount.setVisibility(View.VISIBLE);
notificationCount.setText("0");
}
public void setAlarm(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast( MainActivity.this, 0, alarmIntent, 0);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR, 18); // At the hour you wanna fire
alarmStartTime.set(Calendar.MINUTE, 00); // Particular minute
alarmStartTime.set(Calendar.SECOND, 0);
// alarmStartTime.add(Calendar.MINUTE, 2);
alarmManager.setRepeating(AlarmManager.RTC, alarmStartTime.getTimeInMillis(), getInterval(), pendingIntent);
//Log.i(TAG,"Alarms set every two minutes.");
}
private int getInterval(){
int seconds = 60;
int milliseconds = 1000;
int repeatMS = seconds * 1440 * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
updateUI();
}
public void cancelNotifications(){
Log.i(TAG,"All notifications cancelled.");
}
public void updateUI(){
MyAlarm app = (MyAlarm)getApplicationContext();
mNotificationCount = app.getNotificationCount();
notificationCount.setText(Integer.toString(mNotificationCount));
}
#Override
protected void onResume(){
super.onResume();
if(this.getIntent().getExtras() != null){
Log.i(TAG,"extras: " + this.getIntent().getExtras());
updateUI();
}
}
}
when try the code given in the example it works perfectly hwoever when i try to fire a notification i just wont show up what error
I have read most posts re this issue, but still can't get my implementation working, can you please help?
Basically I want to initiate a BroadcastReceiver from within an Activity, to do something every 10 seconds. So I set the Alarm, but the code never actually reaches "onReceive()"... I can't spot any difference in my code from other examples, could you please take a look?
Also just to mention that I haven't put a receiver in the manifest file, as I understand that it is not needed since I register it within the activity.
Thank you!
package alarm.in;
import alarm.in.activity.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class activityActivity extends Activity {
private Alarm alarm;
private static final String TAG = "AlarmInActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarm = new Alarm();
}
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(ALARM_SERVICE);
registerReceiver(alarm, filter);
}
public void onPause() {
super.onPause();
this.unregisterReceiver(alarm);
}
public void setAlarm(View view){
alarm.SetAlarm(getBaseContext(),1,10);
}
public void cancelAlarm(View view){
alarm.CancelAlarm(getBaseContext());
}
private class Alarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
Log.d(TAG, "Alarm Worked!");
wl.release();
}
public void SetAlarm(Context context, int minutes, int seconds)
{
AlarmManager am=(AlarmManager)context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * seconds * minutes, pi); // Millisec * Second * Minute
Log.d(TAG, "AlarmSet");
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
Log.d(TAG, "AlarmCancel");
}
}
}
You registered your receiver, but forgot to send the action to the receiver:
Intent intent = new Intent(ALARM_SERVICE);
sendBroadcast(intent);
I am trying to update a service from an activity. The Activity saves data to the sql lite database on the phone when the user clicks on a button. What I would like to do here, is when this button is clicked, the service is refreshed and uses the new data.
I was using start/stopservice on the button, but the app crashes and skips around to different activities.
I thought my question was similar to Android: Update / Refresh a running service and
Broadcast Receiver within a Service
However, I'm not updating a widget or another android native component. The service is a custom class.
Please note that a Broadcast receiver starts this service on Boot of the phone.
Also, Logcat window dosen't scroll the readouts. It jerks up and down. So I don't have an error log to show you.
How do I create a function that would allow the service to update when the user clicks on the button in an activity?
Here is my activity (button is at the bottom):
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.joda.time.DateTime;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gcm.demo.app.R;
import com.google.android.gcm.demo.app.EventList.DataView;
import com.google.android.gcm.demo.app.EventList.EventDetails;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
public class AlertDetails extends Activity {
Integer id;
String name;
String date;
String startTime;
String endTime;
String location;
int alertState;
Bundle bundle;
String alertTime;
String s;
private TextView mTitleDisplay;
private TextView mDateDisplay;
private TextView mTimeDisplay;
private TextView mTimeEndDisplay;
private TextView mLocationDisplay;
private TextView mAlertDisplay;
private String update_alarmTime;
String eventYear;
String eventDay;
String eventMonth;
String eventdate;
Context context;
Intent alarmServiceControl;
DatabaseSqlite entry = new DatabaseSqlite(AlertDetails.this);
// Intent startServiceIntent = new Intent(context, AlarmsService.class);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertview);
bundle = getIntent().getExtras();
id = bundle.getInt("id");
name = bundle.getString("eventName");
date = bundle.getString("date");
startTime = bundle.getString("startTime");
endTime = bundle.getString("endTime");
location = bundle.getString("location");
alertState = bundle.getInt("alertState");
alertTime = bundle.getString("alertTime");
alertTime = "10:00:00";// need to be hooked up correctly to get the right
// capture our View elements
mTitleDisplay = (TextView) findViewById(R.id.titleDisplay);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mTimeEndDisplay = (TextView) findViewById(R.id.timeEndDisplay);
mLocationDisplay = (TextView) findViewById(R.id.locationDisplay);
mAlertDisplay = (TextView) findViewById(R.id.alertDisplay);
// set start
mTimeDisplay.setText(startTime);
mTimeEndDisplay.setText(endTime);
// set title
mTitleDisplay.setText(name);
// set Date
eventYear = date.substring(0, 4);
eventDay = date.substring(5, 7);
eventMonth = date.substring(8, 10);
mDateDisplay.setText(eventDay + "-" + eventMonth + "-" + eventYear);
eventdate = eventDay + "/" + eventMonth + "/" + eventYear;
// set location
mLocationDisplay.setText(location);
if (alertState == 0) {
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
entry.close();
}
if (alertState == 1) {
mAlertDisplay.setText("Alert is OFF");
}
Button button1 = (Button) findViewById(R.id.btnSetAlert);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (alertState == 0) {
alertState++;
mAlertDisplay.setText("Alert is OFF");
entry.open();
entry.updateAlertState(id, alertState);
entry.close();
} else {
//turn alarm on
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
alertState = 0;
entry.updateAlertState(id, alertState);
entry.close();
}
// TODO check if service is running
stopService(new Intent(AlertDetails.this,
AlarmsService.class));
startService(new Intent(AlertDetails.this,
AlarmsService.class));
Intent intent = new Intent(AlertDetails.this,
AlertView.class);
startActivity(intent);
}
});
}
}
Here is the service I'd like to update:
package com.google.android.gcm.demo.app.Alerts;
import java.util.Calendar;
import java.util.List;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class AlarmsService extends Service {
DatabaseSqlite db = new DatabaseSqlite(this);
List<Alerts> listAlerts;
PendingIntent pendingIntent;
String tag = "alerttService";
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Created from Alerts service ...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "started onstart command Created from Alerts service .");
return super.onStartCommand(intent, flags, startId);// START_STICKY;
}
#Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Created from Alerts service started...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service started. ..");
// for looops
Thread thread = new Thread() {
#Override
public void run() {
Boolean x = true;
while (x) {
db.open();
listAlerts = db.getAlarmsForService();
db.close();
int alerts=listAlerts.size();
for (int i = 0; i < alerts; i++) {
Alerts item = listAlerts.get(i);
item.getRowId();
item.getRemoteServerId();
String alertInMills = item.getAlertDateInMills();
String alertDuration = item.getAlertDurationInMinutes();
String eventName = item.getEventName();
// intent.putExtra("eventState", item.getEventState());
// intent.putExtra("startTime", item.getStartTime());
// intent.putExtra("alertState", item.getAlertState());
// intent.putExtra("eventName", item.getEventName());
// intent.putExtra("location", item.getLocation());
// intent.putExtra("alertTime", item.getAlertTime());
// intent.putExtra("date", item.getDate());
long longAlertInMills = Long.parseLong(alertInMills);
pendingIntent = PendingIntent.getService(AlarmsService.this, 0,intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
// go to data base for time in mills
calendar.setTimeInMillis(longAlertInMills);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
//
System.out.println(calendar.toString());
}
//
System.out.println("thread");
x = false;
}
}
};
thread.start();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
BroadCast Receiver:
package com.google.android.gcm.demo.app.Alerts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmsBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
Intent startServiceIntent;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
startServiceIntent = new Intent(context, AlarmsService.class);
context.startService(startServiceIntent);
Log.d("TAG", "alarmBroadcastReceiver");
System.out.println("alarm broadcast ...");
}
}
}