I am working on an app which will set the alarm automatically. I have googled a lot and found some solution and made some changes and prepare a code but this code is not working. It is always toasting a message Alarm is null .
Do not know why, can any one please help me out of this? Thanks in advance:
Here is the code :
AlarmManagerBroadcastReceiver Class
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "oneTime";
private Context contx;
public void AlarmManagerBroadcastReceiver()
{
}
#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, "YOUR TAG");
//Acquire the lock
wl.acquire();
//You can do the processing here.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
//Make sure this intent has been sent by the one-time timer button.
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 5 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
}
Main Activity:
import com.test.alarmtest.AlarmManagerBroadcastReceiver;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private AlarmManagerBroadcastReceiver alarm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new CameraPreview(this));
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void alarm(View view) {
AlarmManagerBroadcastReceiver alarmclock = new AlarmManagerBroadcastReceiver();
if(alarm != null){
alarm.SetAlarm(getBaseContext());
}else{
Toast.makeText(getBaseContext(), "Alarm is null", Toast.LENGTH_SHORT).show();
}
}
}
Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.test.cameraapp.MainActivity" >
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_marginRight="23dp"
android:layout_toLeftOf="#+id/button1"
android:text="setAlarm"
android:onClick="alarm" />
</RelativeLayout>
You are checking for alarm but should be checking for alarmclock as that is what you created in this line:
AlarmManagerBroadcastReceiver alarmclock = new AlarmManagerBroadcastReceiver();
Change your if statement to the following
if(alarmclock != null) {
alarmclock.SetAlarm(getBaseContext());
}
else {
Toast.makeText(getBaseContext(), "Alarm is null", Toast.LENGTH_SHORT).show();
}
Related
I have this application to create notifications but I need to keep them when the smartphone turn on/restart. I tried to create a service and auto-start the app when the smartphone turn on but is useless. What can I do?
this is the code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
Button guardar, cancelar;
EditText nota;
ListView lista;
ArrayList<String> notas;
ArrayAdapter<String> adaptador;
NotificationManager notificationManager;
SharedPreferences preferencias;
SharedPreferences.Editor editor;
int cpos; //cantidad de posiciones ya guardadas
Intent intent;
PendingIntent pIntent;
Notification n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista = (ListView) findViewById(R.id.lista);
notas = new ArrayList<String>();
adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, notas);
lista.setAdapter(adaptador);
preferencias = getSharedPreferences("notas", 0);
editor = getSharedPreferences("notas", 0).edit();
cpos = preferencias.getInt("posicionesT", -1);
for(int i = 0; i <= cpos; i++)
{
notas.add(preferencias.getString(Integer.toString(i), ""));
adaptador.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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.
if(item.getItemId() == R.id.add)
{
LayoutInflater inflater = getLayoutInflater();
View dialog = inflater.inflate(R.layout.nota, null);
guardar = (Button) dialog.findViewById(R.id.guardar);
cancelar = (Button) dialog.findViewById(R.id.cancelar);
nota = (EditText) dialog.findViewById(R.id.nota);
cancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
guardar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notas.add(nota.getText().toString());
adaptador.notifyDataSetChanged();
cpos++;
editor.putInt("posicionesT", cpos);
editor.putString(Integer.toString(cpos), nota.getText().toString());
editor.commit();
intent = new Intent(getApplicationContext(), MainActivity.class);
pIntent = PendingIntent.getActivity(getApplicationContext(), (int) System.currentTimeMillis(), intent, 0);
n = new Notification.Builder(getApplicationContext())
.setContentTitle("Recordar")
.setStyle(new Notification.BigTextStyle().bigText(nota.getText()))
.setSmallIcon(R.drawable.ic_icono)
.setContentIntent(pIntent)
.setColor(Color.parseColor("#4CAF50"))
.setOngoing(true) //notificacion persistente
.addAction(R.drawable.ic_borrar, "Quitar nota", pIntent).build();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(cpos, n);
}
});
AlertDialog.Builder alerta = new AlertDialog.Builder(MainActivity.this);
alerta.setView(dialog);
alerta.show();
}
return super.onOptionsItemSelected(item);
}
}
Notifications don't last around restart. TO make what you want happen you need to
1)Write the notifications to disk in some matter (shared preferences,database, file, whatever) when you get one
2)Remove them when the notification is canceled, so you don't redisplay on accident.
3)Write a BOOT_COMPLETE broadcast receiver. Have it read the stored notifications and create new ones with the same info
I've tried to make an app that opens up a service, that changes the wallpaper on your phone every 5 hours.
For testing purposes I've only changed the timer for 1 minute just to see if it works (because when it's on 5 hours it doesn't work),
and indeed it changes the wallpaper every single minute. Even when I close my app and the service is closed
I have a statement to restart it so that works.
Unfortunately when the phone turns black (timeout for the screen). and I turn it back on it's like it stuck up all the time. It needed to go inside the listener while the phone was suspended, so it goes inside the timerTask like, 10 times in a row immediately (or the times it was offline..and it should have gone inside). In other words if I put the phone on rest for 10 minutes and then turn it back on, it will just change my wallpaper 10 times in a row.
So that's one problem. The other one is that if I change the timer for 5 hours it doesn't change the wallpaper at all.
Can someone help me or know why this is happening to me ?
this is my code >
my service >
package com.greenroad.candidate.mywallpaperchanger;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by pitsponet on 31/08/2015.
*/
public class myService extends Service {
int oneSecond = 1000;
int oneMinute = oneSecond*60;
int oneHour = oneMinute*60;
int timerDeley = oneMinute;
private Timer timer;
//this is the tast or the reciver the timer will go into every time it has being called
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
//shows a toast saying timer listener has entered
Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "timer listener Entered", Toast.LENGTH_LONG).show();
}
});
//gets the picture modifire to know what picture to choose to change the wallpaper to
// Access the default SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Integer pictureModifireInt = pref.getInt("pictureModifire", 0);
//updates teh picture modifire by one
pictureModifireInt++;
/////holds a list with all the images that are avilable to change
int displayPicture = R.drawable.captain;
ArrayList<Integer> pictureNames = new ArrayList<>();
pictureNames.add(R.drawable.captain);
pictureNames.add(R.drawable.flash);
pictureNames.add(R.drawable.superman);
pictureNames.add(R.drawable.thor);
pictureNames.add(R.drawable.wonder);
pictureNames.add(R.drawable.a);
pictureNames.add(R.drawable.b);
pictureNames.add(R.drawable.c);
pictureNames.add(R.drawable.d);
pictureNames.add(R.drawable.e);
pictureNames.add(R.drawable.f);
pictureNames.add(R.drawable.g);
pictureNames.add(R.drawable.h);
pictureNames.add(R.drawable.i);
pictureNames.add(R.drawable.j);
pictureNames.add(R.drawable.k);
pictureNames.add(R.drawable.l);
pictureNames.add(R.drawable.m);
pictureNames.add(R.drawable.n);
pictureNames.add(R.drawable.o);
//logs the stored prefrence and select the correct image at place > picture modifire
Log.d("myLog", "storedPreference: " + pictureModifireInt);
displayPicture = pictureNames.get(pictureModifireInt-1);
//stores the picture modifire back in the shared prefrences or initlizes it if it reached the last image
if(pictureModifireInt > 19){
// Edit the saved preferences
Log.d("myLog", "putting in pictureModifire : : " + 0);
editor.putInt("pictureModifire", 0);
editor.commit();
} else {
Log.d("myLog", "putting in pictureModifire : : " + pictureModifireInt);
editor.putInt("pictureModifire", pictureModifireInt);
editor.commit();
}
//most important part of the code
//gets the dimentions of the phones screen and changes the wallpaper
//it has to get the dimentions so that the wallpaper will be in full screen
//maybe he can't do this part when he is in suspend mode ?
WindowManager wm= (WindowManager) getSystemService(MainActivity.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Bitmap bmap2 = BitmapFactory.decodeResource(getResources(), displayPicture);
Bitmap bitmap = Bitmap.createScaledBitmap(bmap2, width, height, true);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
//just shoes a post to let knnow what wallpaper has been changed, and that the walpaper indeed changed
mainHandler = new Handler(getApplicationContext().getMainLooper());
final Integer finalPictureModifireInt = pictureModifireInt-1;
mainHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "wallpaper changed to : "+ finalPictureModifireInt+" and started a new timer", Toast.LENGTH_LONG).show();
}
});
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//show a toast to indicae that a new service was created
Toast.makeText(getApplicationContext(), "a new service created",
Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyLog", "a new service started");
final Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
//show a toast to indicae that a new service was started
Toast.makeText(getApplicationContext(), "serviceStarterd", Toast.LENGTH_LONG).show();
// Access the default SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
//open a boolean to tell if the service is activated for the first time it will say false
boolean serviceStateOn = pref.getBoolean("isServiceActivated", false);
if(serviceStateOn == false){
//if ther serviceStateOn is false then there is no service running and it's fine to run a timer task
Toast.makeText(getApplicationContext(), "a New Timer Started with Delay: "+timerDeley, Toast.LENGTH_LONG).show();
editor.putBoolean("isServiceActivated", true); // getting String
editor.commit();
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, timerDeley, timerDeley);
} else {
//if ther serviceStateOn is true then there is a service runing so just don't do anything
Log.d ("myLog", "Service is on so do nothing");
}
}
});
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "service stoped",
Toast.LENGTH_LONG).show();
}
}
my manifest file >
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.greenroad.candidate.mywallpaperchanger" >
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".myService"
android:exported="false"
/>
</application>
</manifest>
my main acticity >
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//declaring all the buttons
Button comixButtonSuperman, comixButtonFlash, comixButtonCaptainAmerica, comixButtonThor, comixButtonWonderWoman;
Button startServiceButton, stopServiceButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//casting and connecting the buttons to the actual buttons
comixButtonSuperman = (Button) findViewById(R.id.BT_wallpaper1);
comixButtonFlash = (Button) findViewById(R.id.BT_wallpaper2);
comixButtonCaptainAmerica = (Button) findViewById(R.id.BT_wallpaper3);
comixButtonThor = (Button) findViewById(R.id.BT_wallpaper4);
comixButtonWonderWoman = (Button) findViewById(R.id.BT_wallpaper5);
startServiceButton = (Button) findViewById(R.id.BT_startService);
stopServiceButton = (Button) findViewById(R.id.BT_stopService);
//adding listeners for all the buttons
comixButtonSuperman.setOnClickListener(this);
comixButtonFlash.setOnClickListener(this);
comixButtonCaptainAmerica.setOnClickListener(this);
comixButtonThor.setOnClickListener(this);
comixButtonWonderWoman.setOnClickListener(this);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d ("myLog", "Application exists here");
// when going to suspend the service is destroyd, so we should change the boolean to indicate this
//also this will make the service statement added in the service possible.
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor7 = pref.edit();
editor7.putBoolean("isServiceActivated", false); // getting String
editor7.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//maybe will add options in a later date
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.BT_wallpaper1: // superman button
//was used for testings
break;
case R.id.BT_wallpaper2: // flash button
//was used for testings
break;
case R.id.BT_wallpaper3: // captain america button
//was used for testings
break;
case R.id.BT_wallpaper4: // thor button
//was used for testings
break;
case R.id.BT_wallpaper5: // wonder woman button
//was used for testings
break;
case R.id.BT_startService: // starts the service
//starts the service up
Intent i= new Intent(this, myService.class);
startService(i);
break;
case R.id.BT_stopService: // stops the service
//stop the service
Intent j= new Intent(this, myService.class);
stopService(j);
//updates ths shared prefrence that there is no service suning any moew
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor7 = pref.edit();
editor7.putBoolean("isServiceActivated", false); // getting String
editor7.commit();
break;
}
}
}
I believe for this case you should use the AlarmManager instead of timer + handler. It gives you a way to perform time-based operations outside the lifetime of your application.
Here is an example of scheduling using AlarmManager
https://stackoverflow.com/a/8801990/1163224
I decided to add as nipped of code how to use AlarmManager to make my answer more complete
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public 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();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.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 * 60 * 10, pi); // Millisec * Second * Minute
}
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(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Add to Manifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<receiver android:process=":remote" android:name=".Alarm"></receiver>
Service
public class YourService extends Service
{
Alarm alarm = new Alarm();
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.SetAlarm(this);
return START_STICKY;
}
....
}
In the Link above is a full code of how to create a service and start a service on boot
Hope you find my answer useful. :)
I want to get the id of broadcastriver.
Is there any way to find the id of the broadcastreciver?? I am making an alarm application and on saving the alarm, I send a broadcast using pending intent. Now if a user edit the alarm, I want to abort that specif broadcast and send a new broadcast of the new time?
How can I do this????
I am using this code for broadcast
Intent intent = new Intent(this, StartProfileBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, StartTimemill, pendingIntent);
and in manifest, I register my Broadcastreciver using this code
<receiver android:name="StartProfileBroadcastReceiver" >
</receiver>
you can find the project on my github by this project you can et lots of alarm and can catch cancaled alarms.
Alarm class is needed to hold to get specific data
Alarm.java
public class Alarm {
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public int getUniqueID() {
return uniqueID;
}
public void setUniqueID(int uniqueID) {
this.uniqueID = uniqueID;
}
private int state;
private int uniqueID;
}
AlarmHolder is singleton and holds the alarm in an arraylist
AlarmHolder.java
import java.util.ArrayList;
public class AlarmHolder{
private static AlarmHolder uniqueAlarmHolder;
private ArrayList<Alarm> lAlarms;
private AlarmHolder() {
lAlarms = new ArrayList<Alarm>();
}
public synchronized static AlarmHolder getInstance()
{
if (uniqueAlarmHolder == null) {
uniqueAlarmHolder = new AlarmHolder();
}
return uniqueAlarmHolder;
}
public void registerAlarm(int id) {
Alarm a = new Alarm();
a.setState(1);
a.setUniqueID(id);
lAlarms.add(a);
}
public void removeAlarm(int id,Alarm a) {
Alarm newAlarm = new Alarm();
a.setState(0);
a.setUniqueID(id);
lAlarms.remove(id);
lAlarms.add(newAlarm);
}
public void replaceList(ArrayList<Alarm> newList) {
lAlarms.clear();
lAlarms.addAll(newList);
}
public ArrayList<Alarm> getAlarms() {
return lAlarms;
}
public Alarm lastAlarmId() {
return lAlarms.get(lAlarms.size()-1);
}
}
MyBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
AlarmHolder objAlarmHolder = AlarmHolder.getInstance();
#Override
public void onReceive(Context context, Intent intent) {
// with this key we can catch the alarm which we want
int key = intent.getIntExtra("key",0);
for (Alarm alarm : objAlarmHolder.getAlarms()) {
// if alarmstate is 1 and the key belogs that alarm device will vibrate
if (alarm.getState() == 1 & alarm.getUniqueID() == key ) {
Log.v("alarm", String.valueOf(String.valueOf(alarm.getUniqueID())));
Toast.makeText(context, "your alarm id : " + String.valueOf(alarm.getUniqueID()),Toast.LENGTH_LONG).show();
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
} else {
Log.v("alarm", "canceled alarm number : " + String.valueOf(alarm.getUniqueID()));
}
}
}
}
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText text;
int uniqueInteger = 1;
AlarmHolder objAlarmHolder = AlarmHolder.getInstance();
ArrayList<Alarm> tempAlarmHolder = new ArrayList<Alarm>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// we should pass unique integer to method
startAlert(uniqueInteger);
uniqueInteger++;
}
});
}
public void startAlert(int rnd) {
int i = Integer.parseInt(text.getText().toString());
Bundle bundle = new Bundle();
bundle.putInt("key", uniqueInteger);
objAlarmHolder.registerAlarm(uniqueInteger);
int alarmCount = 0;
tempAlarmHolder.clear();
// in this loop, all old alarms' state will set as 0
for (Alarm alarm : objAlarmHolder.getAlarms()) {
if(alarmCount < objAlarmHolder.getAlarms().size()-1)
{
Alarm objAlarm = new Alarm();
objAlarm.setState(0);
objAlarm.setUniqueID(alarmCount);
tempAlarmHolder.add(objAlarm);
}
else
{
tempAlarmHolder.add(alarm);
}
alarmCount++;
}
objAlarmHolder.replaceList(tempAlarmHolder);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), getPendingIntent(bundle, uniqueInteger));
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
}
private PendingIntent getPendingIntent(Bundle bundle, int rc) {
Intent intent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
// send alarm id to broatcast
intent.putExtras(bundle);
return PendingIntent.getBroadcast(this, rc, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
Manifest.xml
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.VIBRATE" ></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
You can either:
Keep a reference to the PendingIntent object you register with the AlarmManager, and call PendingIntent.cancel to cancel it when you're registering a new alarm.
Use the flag FLAG_CANCEL_CURRENT when creating your PendingIntent.
Using both methods, the old alarm will be deleted when creating the new one..
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 ...");
}
}
}
My question is, I want toast message to be displayed when alarm is set to rings for android..I have AnCal alarm application ..I have tried a lot but its not working ...I need your help...
Thanks and regard
Sarfaraz
I am giving you an example that will set alarm every 30 seconds and when the alarm will ring the toast will appear and when alarm will be set notification will be pushed. If I misunderstood your question post comment so i can delete this answer to avoid UN-necessary post.
Step 1 MainActivity.java
package com.example.alarmmanager;
import com.example.alarmmanager.NotificationReceiverActivity;
import com.example.alarmmanager.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private AlarmManagerBroadcastReceiver alarm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarm = new AlarmManagerBroadcastReceiver();
}
#Override
protected void onStart() {
super.onStart();
}
public void startRepeatingTimer(View view) {
Context context = this.getApplicationContext();
if(alarm != null){
alarm.SetAlarm(context);
}else{
Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
}
}
public void cancelRepeatingTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.CancelAlarm(context);
}else{
Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
}
}
public void onetimeTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.setOnetimeTimer(context);
createNotification(view);
}else{
Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show();
}
}
public void createNotification(View view) {
/*********** Create notification ***********/
final NotificationManager mgr=
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.ic_launcher,
"Android Example Status message!",
System.currentTimeMillis());
// This pending intent will open after notification click
PendingIntent i= PendingIntent.getActivity(this, 0,
new Intent(this, NotificationReceiverActivity.class),
0);
note.setLatestEventInfo(this, "Android Example Notification Title",
"This is the android example notification message", i);
//After uncomment this line you will see number of notification arrived
//note.number=2;
mgr.notify(0, note);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Step 2 AlarmManagerBroadcastReceiver.java
package com.example.alarmmanager;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver{
final public static String ONE_TIME = "onetime";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();
//You can do the processing here update the widget/remote views.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
msgStr.append("One time Timer : ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
//Release the lock
wl.release();
Intent service1 = new Intent(context, NotificationService.class);
context.startService(service1);
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Step 3 NotificationReceiverActivity.java
package com.example.alarmmanager;
import android.app.Activity;
import android.os.Bundle;
public class NotificationReceiverActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
}
}
Step 4 NotificationService.java // this is to push notification you can remove this if you do not want notifications
package com.example.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.os.IBinder;
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
final NotificationManager mgr=
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.ic_launcher,
"Android Example Status message!",
System.currentTimeMillis());
// This pending intent will open after notification click
PendingIntent i= PendingIntent.getActivity(this, 0,
new Intent(this, NotificationReceiverActivity.class),
0);
note.setLatestEventInfo(this, "Android Example Notification Title",
"This is the android example notification message", i);
//After uncomment this line you will see number of notification arrived
note.number=startId;
mgr.notify(0, note);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Step 5 : AndroidManifest.xml
<uses-permission android:name='android.permission.WAKE_LOCK'/>
<receiver android:name="com.example.alarmmanager.AlarmManagerBroadcastReceiver"> </receiver>
<service android:name="com.example.alarmmanager.NotificationService"
android:enabled="true" />
Step 6 activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:onClick="startRepeatingTimer"
android:text="Start Alarm repeating 30 sec" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_marginTop="50dp"
android:layout_toRightOf="#+id/textView1"
android:onClick="cancelRepeatingTimer"
android:text="Cancel Alarm" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="58dp"
android:onClick="onetimeTimer"
android:text="Start One Time Alarm" />
</RelativeLayout>
Step 7 result.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:text="This is the result activity opened from the notification"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="#+id/textView1"></TextView>
</RelativeLayout>
Step 8 Run project