I am trying to learn AlarmManager in android.I came across the doc to understand the use of AlarmManager.ELAPSED_REALTIME_WAKEUP .But when i used this in my app and when the app ran,i clicked the back button thinking that alarm manager will again call the activity after the alarm interval time set here
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+10*1000, alarmIntent);
But nothing happens.Please somenone explain the meaning of AlarmManager.ELAPSED_REALTIME_WAKEUP.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmMgr = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmIntent = PendingIntent.getActivity(this, 0, intent,0);
Log.d("asd","initialized alarmintent");
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+10*1000, alarmIntent);
Log.d("asd", "alarm set");
}
}
AlarmReceiver.java
public class AlarmReceiver extends AppCompatActivity
{
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intent_layout);
Log.d("asd","writing textview");
tv=(TextView)findViewById(R.id.textview);
tv.setText("called");
}
}
I would use AlarmManager.RTC_WAKEUP as opposed to AlarmManager.ELAPSED_REALTIME_WAKEUP. Here is an example of how I was using AlarmManager in a recent app:
MainActivity.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, AlarmReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
mAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// Cancel any existing service(s)
mAlarmManager.cancel(pendingIntent);
// Start service
long alarmTime = System.currentTimeMillis() + 10000L; // 10 seconds from now
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
} else {
mAlarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
}
}
AlarmReceiver.class:
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver() { }
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "AlarmService Triggered.", Toast.LENGTH_SHORT).show();
Log.d(this.getClass().getSimpleName(), "Service triggered");
}
}
it seems like your AlarmReceiver class was extending AppCompatActivity which won't work - you need to extend Broadcast Receiver as I have done. Then, within the onReceive() function in AlarmReceiver, you need to navigate to your desired Activity, like this:
Intent newIntent = new Intent(context, NewActivity.class);
context.startActivity(newIntent);
Try these changes and see if they work!
Your code should work fine.
Make sure you have declared your AlarmReceiver activity in the manifest, something like:
<activity
android:name=".AlarmReceiver"
android:label="#string/title_activity_alarm_receiver"
android:theme="#style/AppTheme.NoActionBar"></activity>
Related
I am having trouble to stop the alarm from ringing even after I have pressed the stopAlarm button. thank you for any help.
This is my start alarm switch in MainActivity java class.
public void switchClicked (View view) {
if (((Switch) view).isChecked()) {
Log.d("MainActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
setAlarmText("ON");
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("OFF");
Log.d("MainActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
Here is my StopAlarm button in MainActivity java class.
public void stopAlarm(View view) {
setAlarmText("Alarm stopped");
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
This is the AlarmReciver java class.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
MainActivity inst = MainActivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
The problem is in this line
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You are using getService() but you should use getBroadcast() instead.
Why?
getService() retrieves a PendingIntent that will start a service, but since you are using a BroadcastReceiver you should use getBroadcast() that retrieves a PendingIntent that will perform a broadcast.
I create 2 app (appA, appB) , from appA i send message to appB, in appB a catch this message and create notification , but i want on i click notification open my appA and see my message.
appA
public class MainActivity extends Activity {
TextView text;
Button send;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.editText);
send = (Button) findViewById(R.id.button);
View.OnClickListener Onlistbtn = new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(view.getContext(),Main2Activity.class);
intent.putExtra("com.example.abc.send_messege.broadcast.Message",text.getText().toString());
intent.setAction("com.example.abc.send_messege.custom_action");
sendBroadcast(intent);
}
};
send.setOnClickListener(Onlistbtn);
}}
appB
public class MyReceiver extends BroadcastReceiver {
private final static AtomicInteger c = new AtomicInteger(3);
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
String text = intent.getStringExtra("com.example.abc.send_messege.broadcast.Message");
//Intent intent1 = new Intent(context, Main2Activity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.alert_dark_frame)
.setContentTitle("My notification")
.setContentText(text)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(getID(), mBuilder.build());
}
public static int getID() {
return c.incrementAndGet();
}}
AndroidManifest appB
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.abc.send_messege.custom_action" />
</intent-filter>
</receiver>
Ok you can try this
We you are creating the PendingIntent pass the new intent to launch activity from another application(appA)
Intent intent = new Intent();
//com.colisa.broadcast is the package of another app
//com.colisa.broadcast.MainActivity is the actity to be launched
intent.setComponent(
new ComponentName("com.colisa.broadcast","com.colisa.broadcast.MainActivity"));
Then you will pass it to the PengingIntent.setContentIntent(intent)
I haven't triend this but i think you can intent.putExtra(key, message) and on receiving Activity get that messsage via (this post)
if (null != getIntent().getExtras().getString(key)){
// whatever
}
I broadcast an Intent : com.ss.CUSTOM_INTENT
/*-----Class BroadcastReceiverApp-------*/<br/>
public class BroadcastReceiverApp extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.broadcast_activity);
}
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}*/
// broadcast a custom intent.
public void broadcastIntent(View view){
Intent intent = new Intent();
intent.setAction("com.ss.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
/*------------------------*/
But when I receive that broadcast intent, I want it to be shown in notification drawer.
The Receiver class can extend only BroadcastReceiver class, hence it is now allowing to extend Activity class there by I cannot use:
Context context = getApplicationContext();
which is to be further used in Notification.Builder(context)....
This is my the Broadcast Receiver class:
public class MyReceiver extends BroadcastReceiver , Activity{
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";
Context cont = getApplicationContext();
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent = PendingIntent.getActivity(
MyReceiver.this,
0,
myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification = new Notification.Builder(context)
.setContentTitle("Exercise of Notification!")
.setContentText("http://android-er.blogspot.com/")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
Log.i(getClass().getSimpleName(),"Sucessfully Changed Time");
}
}
Can anyone help in this ? I want to later change the broadcast intent to "android.intent.action.DATE_CHANGED/TIME_CHANGED" which is even not working.
But when I receive that broadcast intent, I want it to be
shown in notification drawer.
If your question is "how to update the gui from a BroadcastReceiver" you have to put the BroadcastReceiver class inside the Activity that you want to update.
The nested BroadcastReceiver class can access the elements of the outer Activity.
For an example see
Android BroadcastReceiver within Activity
I can't stop my service with stopService(). I have tryed everything but it doesn't work. I stop my service only when I uninstall app.
public class Refresh extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "NESTO!", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Your location is: "+MyLocation(), Toast.LENGTH_LONG).show();
return START_NOT_STICKY;
}
#Override
public void onCreate() {
Intent myService = new Intent(this, Refresh.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0,myService, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 20* 1000, pendingIntent);
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public LatLng MyLocation(){
LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
Location location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return new LatLng(location.getLatitude(), location.getLongitude());
}
}
And this is methods in main activity:
public void startService(){
startService(new Intent(getBaseContext(), Refresh.class));
}
public void stopService(){
stopService(new Intent(getBaseContext(),Refresh.class));
}
And this is how I call methods start and stop service:
public void onClick(View V){
stopService();
}
I think the alarm manager you are using to start the service is restarting the service for you,You have to stop that alarm,Stop the alarm like this
Intent intent = new Intent(this, YourService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1253, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pass the SAME ID FOR THE PENDING INTENT which you used while creating the pending intent
You kill the service, but the alarm is still set, you have to cancel the pending intent from the alarm manager in onDestroy
You have to cancel your AlarmManager, so service will not restart every 20sec.
After that you can use stopService() just please insert what service you want to stop.
Create a intent...
Intent intent = new Intent(getBaseContext(), Refresh .class);
When you want to start the service:
startService(intent);
When you want to stop the service:
stopService(intent);
and again, cancel your AlarmManager :) do it before you call stopService();
alarm.cancel(pendingIntent);
Alarm can restart the service. You should cancel it.
can anyone help me with a normal alarm clock app that uses TimePicker to set the time ..and also uses intents,etc instead of normal comparisons.This is the code that i've done till now.But this is not working. The 'TimePicker' sets the time and on pressing the 'ToggleButton' a 'TextVew' shows that alarm is on .But when the alarmtime is reached,Alarm Ringing message is not shown.Please someone help me out.
this is the code of main activity
public class FullscreenActivity extends Activity implements OnClickListener {
TimePicker TimePickerForGettingTime;
TextView AlarmSet;
TextView AlarmOnOff;
ToggleButton ConfirmButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
TimePickerForGettingTime= (TimePicker)findViewById(R.id.TimePickerForGettingTime);
ConfirmButton = (ToggleButton) findViewById(R.id.ConfirmButton);
ConfirmButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{ boolean on=((ToggleButton) v).isChecked() ;
AlarmOnOff=(TextView)findViewById(R.id.AlarmOnOff);
if(on)
{
AlarmOnOff.setText("Alarm on");
Calendar cal = Calendar.getInstance();
cal.set(TimePickerForGettingTime.getCurrentHour(),TimePickerForGettingTime.getCurrentMinute(),00);
setAlarm(cal);
}
else
{
AlarmOnOff.setText("Alarm off");
}
}
});
}
private void setAlarm(Calendar targetCal)
{
Intent alarmintent = new Intent(FullscreenActivity.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(FullscreenActivity.this, 0, alarmintent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
this is the onbootreceiver class
public class OnBootReceiver extends BroadcastReceiver {
private static final int PERIOD=10000; // 10sec
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
}
}
this is the alarmreceiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
NotificationManager manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
Notification noti = new Notification(android.R.drawable.stat_notify_more, "Wake up alarm", System.currentTimeMillis());
noti.setLatestEventInfo(context, "My Alarm", "WAKE UP...!!!", sender);
noti.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(R.string.app_name, noti);
//intent to call the activity which shows on ringing
Intent myIntent = new Intent(context, FullscreenActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
//display that alarm is ringing
Toast.makeText(context, "Alarm Ringing...!!!", Toast.LENGTH_LONG).show();
}
}
Have you registered the alarm receiver in you manifest ?
You should have this in your manifest.
<application>
.
.
.
<receiver android:name=".AlarmReceiver" android:process=":remote" />
</application>
Also, I am not sure that is the right way to calendar set, but I could be wrong . I do it like this and it works fine for me
Calendar cal = Calendar.getInstance();
cal.set (Calendar.HOUR_OF_DAY, time_picker.getCurrentHour());
cal.set (Calendar.MINUTE, time_picker.getCurrentMinute());