set notification alert every 24 hours android - 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

Related

Scheduling a task using AlarmManager

I am trying to schedule a task " a toast message" to appear in the time chosen by the user, but nothing is showing after that time and i can't see what is wrong in the code.
That's my code
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//set The Calendar to to the wanted time!
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
Intent setMsg = new Intent(MainActivity.this, TaskReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setMsg, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setExact(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis(), pendingIntent);
}
}
public class TaskReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "it is working!", Toast.LENGTH_SHORT).show();
}
}
If there is a better way to schedule such a task please go ahead and introduce it.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.yourcomp.yourapp.R;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TestAct extends Activity {
private static class MyHandler extends Handler{
private WeakReference<Activity> activityWr;
public MyHandler(Activity activityMain){
activityWr = new WeakReference<>(activityMain);
}
#Override
public void handleMessage(Message inputMessage) {
if (activityWr.get() != null){
Toast.makeText(activityWr.get(),"Your text",Toast.LENGTH_LONG).show();
}
}
}
private MyHandler mHandler;
private Future<?> mToastTaskRef;
private static int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
/**
* initialize UI & take input from user && call method
*/
}
private void showToastAfterUserSpecifiedDelay(int seconds){
mToastTaskRef = Executors.newScheduledThreadPool(NUMBER_OF_CORES).scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
mHandler.sendMessage(new Message());
}
}, /**initial delay*/60
,/**time*/seconds
,/**time unit*/ TimeUnit.MILLISECONDS);
}
private void stopToastTask(){
if (mToastTaskRef != null && !mToastTaskRef.isCancelled() && !mToastTaskRef.isDone()){
mToastTaskRef.cancel(true); //tru -- >interrupt even if it's running
}
}
}
Use this in your code Instead of manager.setExact method as follows:
manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);

background services stop when the app is closed via the BACK button

A background service in Android stops running when the user exits the app using the BACK button. The same service works fine if the app is in foreground or in background (clicking the HOME button).
there are 3 cases:
Keep the app running: every 15 seconds a notification is shown (OK).
Put the app in background by clicking the HOME button: notifications keep showing (OK)
Click the BACK button (this closes the app): the background service is stopped and no more notifications are shown (BUG)
Expected behavior
Also in case #3, the notifications should keep running every 15 seconds.
my entire source is below
MainActivity.java
package com.example.service_demo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private TextView timerValue;
private Button startTimer;
private Button cancleTimer;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapview();
}
private void mapview() {
timerValue = (TextView) findViewById(R.id.timertext);
startTimer = (Button) findViewById(R.id.starttimer);
cancleTimer = (Button) findViewById(R.id.cancletimer);
startTimer.setOnClickListener(this);
cancleTimer.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
i = new Intent(this, SimpleService.class);
if (isMyServiceRunning()) {
Toast.makeText(getBaseContext(), "Service is running,",
Toast.LENGTH_SHORT).show();
registerReceiver(broadcastReceiver, new IntentFilter(
SimpleService.BROADCAST_ACTION));
startTimer.setEnabled(false);
} else {
Toast.makeText(getBaseContext(), "There is no service running",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
if (v == startTimer) {
startTimer.setEnabled(false);
i = new Intent(this, SimpleService.class);
startService(i);
registerReceiver(broadcastReceiver, new IntentFilter(
SimpleService.BROADCAST_ACTION));
} else if (v == cancleTimer) {
i = new Intent(this, SimpleService.class);
stopService(i);
timerValue.setText("00:00:00");
startTimer.setEnabled(true);
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
String str = intent.getStringExtra("textval");
timerValue.setText(str);
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (SimpleService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
i = new Intent(this, SimpleService.class);
startService(i);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
System.exit(0); // system.exit(0) is mendatory for my app so it can't be
// removed
}
}
SimpleService
package com.example.service_demo;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleService extends Service {
private NotificationManager mNM;
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
long basestart = System.currentTimeMillis();
Timer timer = new Timer();
long timeswap = 0L;
int secs = 0;
int mins = 0;
int hour = 0;
Intent intent;
String s;
public static final String BROADCAST_ACTION = "com.example.service_demo.MainActivity";
private int NOTIFICATION = 1;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(BROADCAST_ACTION);
Toast.makeText(this, "Service Started", 2000).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
timer.schedule(new RemindTask(), 0, 1000);
}
});
t.start();
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mNM.cancel(NOTIFICATION);
if (timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
Toast.makeText(this, "Service Stoped", 2000).show();
}
class RemindTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = System.currentTimeMillis() - basestart;
timeSwapBuff = timeswap;
updatedTime = timeSwapBuff + timeInMilliseconds;
secs = (int) (updatedTime / 1000);
mins = secs / 60;
hour = mins / 60;
secs = secs % 60;
mins = mins % 60;
s = "" + String.format("%02d", hour) + ":" + ""
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs);
if (s.equalsIgnoreCase("00:00:15")) {
showNotification();
}
intent.putExtra("textval", s);
sendBroadcast(intent);
}
}
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence text = s;
// Set the icon, scrolling text and timestamp
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher,
text, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, "Notification Label", text,
contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}
In the method onStartCommand() of the service, return START_STICKY.
The service will continue to run until you explicitly call stopSelf() in the service or call stopService() from your activity.
Try implementing foreground service. foreground service
Foreground service displays notification and is never stopped.
Implement this code snippet in your service's onCreate().
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
This works for me:
notifyIntent.setAction(Intent.ACTION_MAIN);
notifyIntent.addCategory(Intent.CATEGORY_LAUNCHER);

Start Broadcast Receiver from within Activity

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

Activity that can update a Service via Button

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 ...");
}
}
}

Alarm Application Android

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.

Categories

Resources