I am trying to make an alarm application, and found this code online. But when I copied it into eclipse, it gives an error on the startAlert method and says "void is an invalid type for the variable startAlert".
package tanvi.alarm;
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;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
public void startAlert(View view) {
EditText text = (EditText) findViewById(R.id.editText1);
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();
}
}
function startAlert should be out side of onCreate..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAlert(view ); //<--------- no need to pass view if function is on same activity
}
public void startAlert(View view) {
EditText text = (EditText) findViewById(R.id.editText1);
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();
}
You should put the function under the onCreate() method, then call it inside the onCreate() method.
Related
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.
I successfully used the AlarmManager to set an alarm in the future and I was able to have a BroadcastReceiver getting called at alarm time. I read that you can use the PowerManager to turn device on in case it went to sleep and use the KeyguardManager to unlock the device.
But I also need to start my app or bring it into foreground. Will this be done automatically? I can not find a hint to this in the Internet.
You can do this by sending a startActivity in your broadcast receiver with your main activity as the intent.
Got it :)
//The Main Activity
public class FullscreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
Context context=this;
Alarm alarm = new Alarm();
public void onDummyButton(View view) {
alarm.SetAlarm(this);
}
}
//The Alarm Receiver
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.util.Calendar;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Log.d("Alarm", "onReceive");
// Put here YOUR code.
// Start the MainActivity
Intent i = new Intent(context, FullscreenActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
}
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);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() + 1000 * 15);
//calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
//calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+1);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
Toast.makeText(context, "Alarm scheduled for: " + calendar.get(Calendar.HOUR_OF_DAY)+':'+calendar.get(Calendar.MINUTE)+':'+calendar.get(Calendar.SECOND), Toast.LENGTH_LONG).show();
}
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);
}
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'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
}