Android AlarmManager - android

Ok, I've tried two examples of AlarmManager- one from the commonsware website, and one from the manning website.
The code I am currently working with is from the manning website : [http://unlocking-android.googlecode.com/svn/chapter8/trunk/SimpleAlarm/][1]
There are two classes, AlarmReceiver and GenerateAlarm. Anyone have any idea why the toast will not display in the emulator? I was thinking that it was because I am located in the Eastern Time Zone and it uses UTC, but I have fiddled with different things and none of them seem to work.
public class GenerateAlarm extends Activity {
Toast mToast;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.set_alarm_button);
button.setOnClickListener(this.mOneShotListener);
}
private OnClickListener mOneShotListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(GenerateAlarm.this, AlarmReceiver.class);
PendingIntent appIntent = PendingIntent.getBroadcast(GenerateAlarm.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// calendar.add(Calendar.MINUTE, 1);
calendar.add(Calendar.SECOND, 10);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), appIntent);
if (GenerateAlarm.this.mToast != null) {
GenerateAlarm.this.mToast.cancel();
}
GenerateAlarm.this.mToast = Toast.makeText(GenerateAlarm.this, R.string.alarm_message, Toast.LENGTH_LONG);
//GenerateAlarm.this.mToast.show();
}
};
}
public class AlarmReceiver extends BroadcastReceiver {
public void onReceiveIntent(Context context, Intent intent) {
Toast.makeText(context, R.string.app_name, Toast.LENGTH_SHORT).show();
}
#Override
public void onReceive(Context context, Intent intent) {
}
}

You have to add your toast in the onReceived method where you should add the handling of the intent received.
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, R.string.app_name, Toast.LENGTH_SHORT).show();
}
onReceiveIntent is not a method of broadcastreceiver
public abstract void onReceive
(Context context, Intent intent)
Since: API Level 1 This method is
called when the BroadcastReceiver is
receiving an Intent broadcast.

Related

Access to BroadcastReceiver method onReceive() in activity

I have written some related code for AlarmManager App.
I want to do something like writting a Toast massage in the activity, for sure i can not do that in onReceive() method the question is that how can i do it in the activity?
public class MainActivity extends AppCompatActivity implements View.OnClickListener,BroadConnect.IsConnect {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vv();
setRecurringAlarm(MainActivity.this);
}
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
//updateTime.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
updateTime.setTimeZone(java.util.TimeZone.getTimeZone("GMT+5:00"));
updateTime.set(Calendar.HOUR_OF_DAY,10);
//updateTime.set(Calendar.MINUTE,31);
updateTime.set(Calendar.MINUTE,1);
updateTime.set(Calendar.SECOND,20);
Intent intent = new Intent(context, BroadConnect.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}
#Override
public void onReceiveTimer() {
Toast.makeText(MainActivity.this,"OK",Toast.LENGTH_LONG).show(); //This will not be displayed
}
}
public class BroadConnect extends BroadcastReceiver {
private IsConnect isConnect;
public interface IsConnect{
void onReceiveTimer();
}
public void setIsConnect(IsConnect isConnect) {
this.isConnect = isConnect;
}
#Override
public void onReceive(Context context, Intent intent) {
isConnect.onReceiveTimer(); //It runs this and makes a ERRORE
}
}

Alarm Manager does not work as expected when scheduling task

I'm currently working with Android Alarm Manager and found a working example. But it does not work properly in my situation. Let me explain. Basically my goal is to execute a method from the MainActivity each 5 mins. For this purpose I use Alarm Manager to schedule that task.
Basically this is the working stuff:
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
}
}
MainActivity.java
public class MainActivity extends Activity{
private PendingIntent pendingIntent;
private AlarmManager manager;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAlarm();
}
});
}
public void startAlarm() {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 300000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Log.d(TAG, "Alarm Set");
}
}
Everything is good. "I'm running" Toast is executed every 300000 ms (5 mins). The AlarmReceiver class send a broadcast to my main Activity with the message "SERVICE_TEMPORARY_STOPPED". I already registered that message in my MainActivity via registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));. But, when I add another method, let's say stopAlarm() in the broadcastReceiver, which is going to stop the alarm after 5 mins, the time interval (5 mins) is not applied anymore. In something like 10 secs, it calls the Broadcast Receiver and stop the alarm. And this is the issue. Take a look at the stop() method and how I call it on the broadcastReceiver:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
stopAlarm();
}
};
public void stopAlarm() {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Log.d(TAG, "Alarm Cancelled");
}
Any clue?
AlarmManager.setRepeating doesn't work properly on different android versions.
Try setExact. It won't repeat but you can achieve repeating functionality as mentioned below:
Updated AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
long repeatCount = PreferenceManager.getDefaultSharedPreferences(context).getLong("REPEAT_COUNT", 0L);
repeatCount++;
PreferenceManager.getDefaultSharedPreferences (context).edit().putLong("REPEAT_COUNT", repeatCount).apply()
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExact(AlarmManager.RTC_WAKEUP, (repeatCount *System.currentTimeMillis()),pendingIntent);
}
}
Here we maintain a repeatCount & variable (preference based) and increment it in your AlarmReceiver & schedule alarm again by calculating nextAlarmTime using repeatCount * System.currentTimeMillis();

Android :: how can I restart service and run specific function at time x

PROBLEM
I want to know some concept to do like the topic said
what should be a requirement to do that
I think that PendingIntent and AlarmManager would be help to restart the service
at time x but I don't know that way to let it call function that I need
Please advice.
FOR EXAMPLE
I have 2 functions in my service class and I want to register it
to run one of these two (Depend on user propose) in the future at time x
SOME CODE THAT I WORK AROUND (EDIT)
public class MyActivity extends Activity implements View.OnClickListener {
private Button b1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button)findViewById(R.id.cmd1);
b1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
startIntentAt(5,MyReceiver.class);
finish();
}
private void startIntentAt(int seconds, Class<?> c) {
Intent myIntent = new Intent(getBaseContext(), c);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),0, myIntent, 0);
AlarmManager alarmManager= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, seconds);
//long interval = 60 * 1000; //
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, TargetActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
}

android alarm not triggered

I am trying to make a simple android alarm app that basically take the time from the user and set an alarm every day in that time
i am using alarmmanger , the app runs fine with no errors but the alarm doesn't work !!
here is the where the user set the time
buttonSet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("syso","1");
String sTime = eReminderTimeAM.getText().toString();
String aTime[] = sTime.split(":");
Log.i("syso","2");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(aTime[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(aTime[1]));
Log.i("syso",aTime[1]);
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent( getBaseContext(), Alarm.class);
alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
Log.i("syso","3");
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
}
});
and here is the other activity that should run
MediaPlayer mp=null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_alarm);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
mp = MediaPlayer.create(getBaseContext(),R.raw.toha);
stopAlarm.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
mp.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(final Context context, Uri alert) {
Thread background = new Thread(new Runnable() {
public void run() {
try {
mp.start();
} catch (Throwable t) {
Log.i("Animation", "Thread exception "+t);
}
}
});
background.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
}
Is "Alarm.class" a "BroadcastReceiver"? else please create a "BroadcastReceiver" and onReceive method of "BroadcastReceiver" call activity
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
Don't forget to add receiver to your Manifest
You have to add the receive class
public class Alarm extends BroadcastReceiver {
private Context context;
#Override
public void onReceive(Context context1, Intent intent) {
context = context1;
}
}
in android manifest also declare the receiver
<receiver android:name="Alarm" >
it was a silly mistake at the end ..
just had to replace PendingIntent.getBroadcast to PendingIntent.getActivity and it worked fine

AlarmManager to start an activity with onBootReceiver

I developed an app to start an activity at everyday 11pm. I also added a boot receiver on it. the output of this app gives nothing but a blank screen. Kindly someone help me.
This is my first class OnBootService
public class boot extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent bootintent) {
Intent mServiceIntent = new Intent();
mServiceIntent.setAction("com.thenga.nilavilak.timer_test001.alarm");
context.startService(mServiceIntent);
}
}
This is my alarm class
public class alarm extends boot {
public void onReceiveboot(final Context context) {
Calendar vtime = Calendar.getInstance();
vtime.set(Calendar.HOUR_OF_DAY,23);
vtime.set(Calendar.MINUTE,0);
vtime.set(Calendar.SECOND,0);
;
PendingIntent pi = PendingIntent.getService(context, 0,
new Intent(context, sasi.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, vtime.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
}
public IBinder onBind(Intent arg0) {
return null;
}
}
This is my third class the want to run at 11 pm
public class sasi extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getApplicationContext(),"Output received",Toast.LENGTH_SHORT).show();
}
}

Categories

Resources