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.
Related
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?
I am trying to follow the example given here on running some code in fixed time intervals. I used the code in this example (setting the waiting time to 1 minute instead), compiled it, started in on my phone, stopped the application on the phone, and waited for several minutes.
However, no Toast was shown and neither any log-entry. I also notice that the Service.onStart seems depreciated.
Is something missing in the example? Do I need to register something when the main activity of the app is started? Or call it from somewhere else in my app? Or maybe something is wrong in the manifest?
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mypackage.test" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application>
android:allowBackup="true"
android:icon="#mipmap/stoxx"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NewEntryActivity"
android:label="#string/menu_add"
android:theme="#style/AppTheme.NoActionBar"
/>
<activity
android:name=".UserSettingActivity"
android:label="#string/menu_add"
android:theme="#style/AppTheme.NoActionBar"
/>
<receiver
android:process=":remote"
android:name=".Alarm">
</receiver>
</application>
</manifest>
You forgot to include service in your Manifest. Here is all this project that works for me, check it.
Here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alarmmanager.just_me.alarmmanager">
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application android:allowBackup="true" android:label="#string/app_name"
android:icon="#mipmap/ic_launcher" android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".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>
<receiver android:process=":remote" android:name=".Alarm"/>
<service android:name=".MyService"/>
</application>
Here is Alarm:
public 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();
// Put here YOUR code.
Toast.makeText(context, "com.alarmmanager.just_me.alarmmanager.Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
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);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5, pi); // Millisec * Second
}
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);
}}
Here is service:
public class MyService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d("!~!", "Service started.");
alarm.SetAlarm(this);
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId)
{
alarm.SetAlarm(this);
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
And the last one MainActivity:
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
}
My program is to listen receive_boot_complete broadcast when device completes the boot.
The program is working fine as expected with android 4.0.3, but the same thing is not happening when I am running the code on Android 4.4.4 device.
The broadcastreceiver is not receiving a boot completed broadcast.
Is there anything new for Android 4.4.4? Running it on Moto G.
My code is as below:
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.app"
android:versionCode="1"
android:installLocation="internalOnly"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:excludeFromRecents="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:label="#string/ser_name"
android:icon="#drawable/serv_ico"
android:enabled="true" />
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name=".AlarmReceiver"
android:enabled="true" >
</receiver>
</application>
BootReceiver
public class BootReceiver extends BroadcastReceiver{
#Override
public void onReceive(final Context context, Intent intent) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Start alarm manager on boot
// Start service
}
}, 60000);
}
}
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
// Start service
}
}
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Run service on application start
setContentView(R.layout.activity_main);
// Initialize alarm manager application start
PackageManager p = getPackageManager(); // Remove App icon from launcher
p.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}
AlarmManager
public class Alarm {
public Alarm schedule(Context context) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 15);
calendar.set(Calendar.SECOND, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi);
return null;
}
}
You have to define your receiver with exported = true and enabled = true
<android:name=".BootReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" />
This might be because of a bug in Android 4.4.4 r1/r2
See
Bug in Android KitKat
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;
}
So i'm setting a repeating alarm to fetch data from a server. The problem is that nothing happens when the alarm is suppose to go off. I get no errors while launching it, and the code is correct (as far as i know).
Here is the code that sets the alarm:
private void startRequestTimer() {
// This is what will be called when the alarm goes off (GetOperations)
Intent intent = new Intent(MainActivity.this, GetOperations.class);
PendingIntent operation = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
// The alarm will go off in one second from now
long firstTime = SystemClock.elapsedRealtime();
firstTime += 1000;
// Set the alarm
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5*1000, operation);
}
Here is GetOperations.java (it's called when the alarm goes off)
package se.jbhalmstad.ndroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class GetOperations extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Oh! The alarm went off!", 2000).show();
}
}
And the manifest, in case i messed something up here (which i doubt, since i'm not getting any errors):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="se.jbhalmstad.ndroid"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="#drawable/icon" android:label="#string/APP_NAME">
<activity android:name=".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=".SettingsActivity" />
<activity android:name=".GetOperations" />
</application>
</manifest>
Have i missed something?
You declared GetOperations as a BroadcastReceiver, but in your Manifest it's an Activity.