BroadcastReceiver and AlarmManager Android - android

I am trying to use an alarm manager with BroadcastReceiver. I try to use the example given in Tutorial: System Services and BroadcastReceiver . but when I run the example after the end of the time the toast doesn't show up. the code is below:
My main Activity:
public class AlarmActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
}
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();
}
}
my broadCastReceiver:
public class MyBroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panic but your time is up!!!!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
my main Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Number of seconds"
android:inputType="numberDecimal" >
</EditText>
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAlert"
android:text="Start Counter" >
</Button>
</LinearLayout>
and the manifestfile:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.broadcastreceiver.AlarmActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.android_alarm.MyBroadcastReceiver" >
</receiver>
</application>
</manifest>

The receiver must extend from BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
// ...
}
Also be sure that receiver name in manifest file is correct.

Your MyBroadcastReceiver class is wrong, edit your MyBroadcastReceiver class to the following:
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panic but your time is up!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
You need to add extends BroadcastReceiver and override onReceive() method.

You just forgot to override OnReceive() method. public void onReceive(Context context, Intent intent) is predefined method of BroadcastReceiver, wheneven you are using it, You must #Override it as follows,
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override // You forgot this line
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Don't panik but your time is up!!!!.",Toast.LENGTH_LONG).show();
}
}

You have created a startAlert function which u didn't call anywhere.So first call that method in onCreate and then you will receive a toast.

Related

When i restart my phone my alarmclock app not working

i was trying to create my own alarm clock in android. The aim is that my alarm clock should play different songs based on my playlist . This is a college project . User sets an alarm and then forgets and then even after multiple restarts the alarm should play . I downloaded a sample code from and was working on this . However on a restart of phone my alarms are getting lost . I found that i need to use broadcast receiver but still its not working on my phone lava phone . Can you please suggest if this code is fine . Here is my code link:https://drive.google.com/file/d/1ADVyH0grEQ4g80HkFU1n2Cb4wxnQC4TX/view?usp=sharing
my android manifest file is..
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alarmmanager">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
my layout file...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="28dp"
android:ems="10"
android:hint="Number of seconds"
android:inputType="numberDecimal" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/time"
android:layout_below="#+id/time"
android:layout_marginRight="60dp"
android:layout_marginTop="120dp"
android:text="Start" />
</RelativeLayout>
my receiver code..
package com.alarmmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import android.widget.Toast;
import java.util.Calendar;
/**
* Created by bhaskar on 24-04-2018.
*
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
#Override
public void onReceive(Context context, Intent intent) {
mp= MediaPlayer.create(context, R.raw.alrm );
mp.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
Log.i("Alarm","Alarm"+ Calendar.getInstance().getTime());
}
}
mainActivity file
public class MainActivity extends AppCompatActivity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startAlert();
}
});
}
public void startAlert() {
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();
}
}
see this official doc for maintaining alarm when phone gets restarted.
in Start an Alarm When the Device Boots section
After getting the actual code i am editing this answer :
1) create new Receiver instead of using old one receiver
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Set the alarm here.
Log.d("AlarmDone", "AlarmDone");
}
}
}
2) register it in manifest file :
<receiver
android:name=".SampleBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
3) change your old receiver code in menifest :
<receiver android:name=".AlarmReceiver" />
Note : add permission in manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
now your alarm will ring.
For me it works only when i enable auto start

Why my WakefulBroadcastReceiver onReceive not called

I have written small example for AlarmManager to work. But my WakefulBroadcastReceiver onReceive is not called at all. Following is my code, Can you pls find out why its not getting called?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wearable.wearables">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name="com.wearable.wearables.AlarmReceiver" />
<activity
android:name=".AlarmActivity"
android:label="#string/title_activity_alarm"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
WakefulBroadcastReceiver
public class AlarmReceiver extends WakefulBroadcastReceiver {
private static final String TAG = "AlarmReceiver";
AlarmManager alarmManager;
PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"AlarmReceiver OnReceive called......");
Intent service = new Intent(context, SchedulingService.class);
startWakefulService(context,service);
}
public void setAlarm(Context context) {
Log.d(TAG,"setAlarm called...");
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
System.currentTimeMillis() + 30000,
60000,
alarmIntent);
}
}
Activity setting Alarm
public class AlarmActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_alarm);
AlarmReceiver alarmReceiver = new AlarmReceiver();
alarmReceiver.setAlarm(this);
}
}
setAlarm method is calling. My intention is I need to call this wakefulService every 30 secs. Issues are
Code is not letting to set 30 secs (allowing only one minute as minimum)
WakefulBroadcastReceiver onReceive() is NOT called at all..
I am struggling with this issue. Can someone help me out with this pls?

AlarmManager never start my Service

In my application, I am trying to start a service using AlarmManager.
The code for AlarmManager is below:
public class Main extends Activity {
...
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5*1000, 5*1000, pintent);
}
...
}
below is the Service Class:
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "MyService.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "MyService.onStart()", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "MyService.onStartCommand()", Toast.LENGTH_LONG).show();
}
}
and the Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.max.android.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.max.android.myapp.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<service android:enabled="true" android:name="com.max.android.myapp.SubsService" />
</manifest>
running adb shell dumpsys alarm I can see my alarm:
RTC_WAKEUP #0: Alarm{41878860 type 0 com.max.android.myapp}
type=0 when=+3s954ms repeatInterval=5000 count=1
operation=PendingIntent{41878850: PendingIntentRecord{41878760 com.max.android.myapp startService}}
But MyService is never started. Why is this not working?
Solved. After looking at adb logcat I've found this warning: W/ActivityManager( 1506): Unable to start service Intent { flg=0x4 cmp=com.max.android.myapp/.SubsService (has extras) }: not found In AndroidManifest.xml, I had the < service> declaration after < application> instead of nested inside it.
SystemClock.elapsedRealtime
Returns milliseconds since boot, including time spent in sleep.
You can get current time in milliseconds by calling
new Date().getTime()
see https://developer.android.com/training/scheduling/alarms.html

Why does my BroadcastReceiver Doesn't work properly?

I'm stuck in this problem for 3 days and I'm so frustrated ..
I don't know why on earth my BroadCastReceiver doesn't work ...
I'll sincerely appreciate solving my problem...
Here is my code..
MainActivity (I posted some pieces of codes from my whole codes.. that I regard as important to understand)
This MainActivity, I get AlarmManager..
:
public class MainActivity extends FragmentActivity implements TabListener{
private GregorianCalendar mCalendar;
private NotificationManager mNotification;
private AlarmManager mManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotification = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//Get AlarmManager here..
mManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
....
..
}
public NotificationManager getNotification(){
return mNotification;
}
public AlarmManager getAlarmManager(){
return mManager;
}
And here is my MsgBookingFragment(this class extends Fragment..) :
//...somewhere else of my codes..
//Access to SQLDataBase and get Date, and set it in bookDate..
bookDate.set(Integer.parseInt(year.split("년")[0]),
Integer.parseInt(month.split("월")[0]),
Integer.parseInt(day.split("일")[0]),
Integer.parseInt(hourOfDay.split("시")[0]),
Integer.parseInt(minute.split("분")[0]));
//get mainActivity, in order to get AlarmManager..
final MainActivity mainActivity = (MainActivity)getActivity();
AlertDialog.Builder alert_confirm = new AlertDialog.Builder(getActivity());
alert_confirm.setMessage("예약 하시겠습니까?").setCancelable(false).setPositiveButton("예",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
doSomething();
msgViewService.write(vo);
Log.i("MsgBookingfragment", "msgViewInputVO write done = " + vo.toString());
FragmentManager FM = getFragmentManager();
FM.popBackStack();
FragmentTransaction ft = FM.beginTransaction();
mainActivity.setHashMapInsert(vo.getPersonID());
mainActivity.setBookedHashInsert(vo.getPersonID());
ft.replace(R.id.findperson, new FindPersonFragment()).commit();
//here, I get AlarmSet Instance and setAlarm..!!
AlarmSet alarm = new AlarmSet(bookDate,
getActivity().getApplicationContext(),
((MainActivity)getActivity()).getAlarmManager(),
((MainActivity)getActivity()).getNotification() );
alarm.setAlarm();
Toast.makeText(getActivity().getApplicationContext(), "예약되었습니다.", Toast.LENGTH_LONG).show();
}
And here is my AlarmSet Class :
public class AlarmSet extends Activity implements OnDateChangedListener, OnTimeChangedListener{
private String tag = "AlarmSet";
private Calendar bookDate = Calendar.getInstance();
private Context context;
private AlarmManager mManager;
private NotificationManager mNotification;
public AlarmSet(Calendar cal, Context c, AlarmManager am, NotificationManager noti){
bookDate = cal;
context = c;
mNotification = noti;
mManager = am;
}
public void setAlarm() {
mManager.set(AlarmManager.RTC_WAKEUP, bookDate.getTimeInMillis(), pendingIntent());
Log.i("setAlarm : ", bookDate.getTime().toString());
//Log shows this message : Sat Oct 18 14:25:52 GMT+09:00 2014
}
//set free Alarm
public void resetAlarm() {
mManager.cancel(pendingIntent());
}
public PendingIntent pendingIntent() {
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getActivity(context, 3 , i, PendingIntent.FLAG_CANCEL_CURRENT);
Log.i(tag, "PendingIntent.......");
return pi;
}
here is my AlarmReceiver :
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("TAg", "ggggggggggggggggggggg");
Toast.makeText(context, R.string.app_name, Toast.LENGTH_SHORT).show();
}
And here is my ManiFast :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.dduo.hrelation"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="org.dduo.hrelation.AlarmReceiver">
<intent-filter>
<action android:name="action"/>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
So long pieces of codes...
By the way, I reckon it's so doubtful of pendingIntent method... I guess the problem is because of that method.. I've never seen that "ggggggggg" log msg.. and toast msg on my test device..
Please... help me..
in ManiFast :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.dduo.hrelation"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
//---> declare broadcast receiver like this
<receiver android:name="org.dduo.hrelation.AlarmReceiver">
</receiver>
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and pendingIntent():
public PendingIntent pendingIntent() {
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
Log.i(tag, "PendingIntent.......");
return pi;
}

Alarm doesn't trigger the AlarmReveicer

I am coding a simple alarm test in android, but as mentionned in the title the AlarmReceiver isn't triggered !
i sought here for the solution but none of them worked since my code seems to be correct ...
here is my code :
public class AlarmActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
Button salarm = (Button) findViewById(R.id.salarm);
final AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(AlarmActivity.this,AlarmReceiver.class);
final PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
salarm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+(1000*5), pi);
Toast.makeText(getApplicationContext(), "Alarm set, wait 5 sec", Toast.LENGTH_SHORT).show();
}
});
}
Manifest file :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtest3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.androidtest3.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>
<activity android:name="AlarmActivity"/>
<receiver
android:exported = "true"
android:name = "AlarmReceiver">
</receiver> <!-- <receiver android:name="AlarmReceiver"/> aurait fait l'affaire -->
</application>
</manifest>
AlarmReceiver Class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "pending intent received !", Toast.LENGTH_SHORT).show();
}
}
it would help if you could explain the any solution you suggest.
thanx
It's likely not happening because the time value is incorrect. If you are going to use RTC_WAKEUP type alarms, get the time using System.currentTimeMillis() plus your additional time. Right now you're using elapsed time, which is not the same as RTC wall clock time.

Categories

Resources