how to set multiple, repeating pending intent using android alarm manager? - android

I'm making an app in which i need to turn my phone into the vibration mode at the scheduled time.
The problem is that only the second pending intent is executed.
How can I start multiple pending intents?
My code:
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class GetSlots extends Activity {
private Calendar mCalendar;
private Calendar nCalendar;
private CheckBox a1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slots);
addenable();
a1 = (CheckBox)findViewById(R.id.checkBox2);
}
#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;
}
public void addenable() {
}
public void getdata(View V) {
mCalendar= Calendar.getInstance();
mCalendar.set(Calendar.HOUR_OF_DAY, 16 );
mCalendar.set(Calendar.MINUTE, 27);
mCalendar.set(Calendar.SECOND, 0);
nCalendar= Calendar.getInstance();
nCalendar.set(Calendar.HOUR_OF_DAY, 16 );
nCalendar.set(Calendar.MINUTE, 29);
nCalendar.set(Calendar.SECOND, 0);
Intent intentAlarm = new Intent();
intentAlarm.setClass(this, AlarmReciever.class);
PendingIntent i = PendingIntent.getBroadcast(this, 0, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent j = PendingIntent.getBroadcast(this, 0, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT);
// create the object
AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if(a1.isChecked()) {
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),500*1000, i);
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, nCalendar.getTimeInMillis(), 1000*1000, j);
Toast.makeText(this, "Alarm Scheduled", Toast.LENGTH_LONG).show();
}
if(!a1.isChecked()) {
PendingIntent.getBroadcast(this, 0, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT).cancel();
}
}
}

Related

2 Calendar show 1 Notification

I have an app work on remind the user with timetable
I put a calendar in new class with notification and go to main activity and called it.
but it the first method only showed the notification but the second not showed it why ????????
MainActivity.java
package com.osman.calendar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.pushbots.push.Pushbots;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Pushbots.sharedInstance().init(this);
new section(this,1, 18, 30,"Title","new message","new message");
new section(this,2, 18, 37,"Title","get new","get new");
}
}
section.java
package com.osman.calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import java.util.Calendar;
public class section {
public section(Context context,int id,int Hours,int Minute, String Tilte , String Text, String Alert){
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("id",id);
intent.putExtra("Title",Tilte);
intent.putExtra("Text",Text);
intent.putExtra("Alert",Alert);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Hours);
calendar.set(Calendar.MINUTE, Minute);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 60 * 24 * 7, alarmIntent);
}
}
AlarmReceiver.java
package com.osman.calendar;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.",Toast.LENGTH_LONG).show();
String Title = intent.getExtras().getString("Title");
String Text = intent.getExtras().getString("Text");
String Alert = intent.getExtras().getString("Alert");
int id = intent.getExtras().getInt("id");
createNotification(context, Title, Text, Alert,id);
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
public void createNotification (Context context, String msg,String msgText, String msgAlert,int id){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(msg)
.setContentText(msgText)
.setTicker(msgAlert);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationMAnger =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationMAnger.notify(id, mBuilder.build());
}
}
If you schedule a alarm with the same PendingIntent as before, the alarm you set before is updated and not a new one is set. Only one alarm is firing because your PendingIntent didn't change when you use it the second time, only the extras change (according to this question's answer this isn't considered a change).
To not update the old alarm but set a new one, you have to use a different request-code (the second parameter in getBroadcast() - currently you use 0 for both alarms).
Just use the id you already have as parameter in your section-constructor as request-code.

How to programatically set the reminder to a specific date

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;
}
}

set notification alert every 24 hours android

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

Notification in android do not work

I am making notification bar in my app and this is my code :
MainActivity:
package com.example.notificationservicedemo;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnClickListener {
EditText editMsg;
DatePicker datePicker;
TimePicker timePicker;
Button btnSetNotification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editMsg = (EditText) findViewById(R.id.editText1);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
btnSetNotification = (Button) findViewById(R.id.buttonSetNotification);
btnSetNotification.setOnClickListener(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 void onClick(View view) {
Intent intent = new Intent();
// TODO Auto-generated method stub
switch(view.getId()){
case R.id.buttonSetNotification:
String message=editMsg.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, datePicker.getMonth());
calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
calendar.set(Calendar.YEAR, datePicker.getYear());
calendar.set(Calendar.HOUR, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentHour());
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
intent.setClass(this, MyNotificationService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
//startService(intent);
break;
}
}
}
MyNotificationService:
package com.example.notificationservicedemo;
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;
import android.widget.Toast;
public class MyNotificationService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "OnCreate()", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "OnStart()", Toast.LENGTH_SHORT).show();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent= new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(R.drawable.ic_launcher, "Bla bla bla", System.currentTimeMillis());
String contentTitle="Title";
String contentText="This is your message";
notification.setLatestEventInfo(this, contentTitle, contentText, pendingIntent);
notificationManager.notify(123, notification);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notificationservicedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.notificationservicedemo.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="com.example.notificationservicedemo.MyNotificationService"></service>
</application>
</manifest>
Problem is that when I pick time when notification has to come up I press my button to save and then notification comes up immediately it ignores my timePicker and datePicker. What is the peoblem?
This is my solution for launch a notification on android :
public class MyNotification {
private NotificationManager nm;
private Notification nf;
private int notification_id;
public MyNotification(Context context, Class<?> cls, int icon, CharSequence tickerText, CharSequence title, CharSequence text, int notification_id) {
nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancelAll();
Intent activity = new Intent(context, cls);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, activity, 0);
Notification.Builder builder = new Notification.Builder(context);
builder.setContentIntent(contentIntent); //-> Activity open after click
builder.setAutoCancel(true);
builder.setSmallIcon(icon);
builder.setWhen(System.currentTimeMillis());
builder.setTicker(tickerText);
builder.setContentTitle(title);
builder.setContentText(text);
//builder.setSound(Uri.parse("android.resource://"+this.getPackageName()+R.raw.good)); //-> Song
//builder.setContent(new RemoteViews(getPackageName(), R.layout.note)); //-> Layout
//builder.setVibrate(new long[]{0, 100, 25, 100}); // -> Vibration
Notification nf = builder.getNotification();
this.nf = nf;
this.notification_id = notification_id;
}
public void show() {
this.nm.notify(notification_id, nf);
}
}
I hope i have helped you!

Develop Alarm Application

I'd like develop an Alarm Application.
The application should work like this:
launch it
the activity show me the time
I can set the alarm
I can close the application
when the alarm time comes , it starts an activity (even if the device is locked)
I have tried to adapt this sample https://github.com/commonsguy/cwac-wakeful but I cannot launch an activity when the alarm time comes.
I use this code to setup the alarm (for test I have inserted this code on an onCreate method of activity):
Intent intent = new Intent(this, OnAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
this is the OnAlarmReceiver class:
public class OnAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(ClockActivity.LOG_TAG, "OnAlarmReceiver::onReceive");
WakefulIntentService.sendWakefulWork(context, AlarmService.class);
}
}
this is the service class:
public class AlarmService extends WakefulIntentService {
public AlarmService(String name) {
super(name);
}
#Override
protected void doWakefulWork(Intent intent) {
Log.i(ClockActivity.LOG_TAG, "AlarmService::doWakefulWork");
Intent newIntent = new Intent(getApplicationContext(), ClockActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.setAction(ClockActivity.ALARM_ACTION);
getApplicationContext().startActivity(newIntent);
}
}
this is the portion of Manifest where are setup the service and the receiver:
<receiver android:name=".OnAlarmReceiver"></receiver>
<service android:name=".AlarmService"></service>
the doWakefulWork method is never called!
I have made this application:
AlarmActivity.java
package com.foo;
import pack.breceiver.MyBroadcastReceiver;
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.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.os.Bundle;
public class AlarmActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startAlert(View view) {
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package pack.breceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panik but your time is up!!!!",
Toast.LENGTH_LONG).show();
/*// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000); */
}
}
check this out : http://blog.nelsondev.net/?p=124
using"alarmmanager"
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
AlarmCal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingAlarmIntent);
I had a similar problem and I resolved removing the receiver from manifest and set in my code registering him with registerReceiver.
Do you get an instantiation exception maybe ?
You should have a public no arg constructor in your service :
public class AlarmService extends WakefulIntentService {
public AlarmService() {
super("AlarmService");
}
// etc
}

Categories

Resources