Reputation: 695
I'd like my app performs some work periodically.To do it I'm using AlarmManager
but for some reason it doesn't fire any events.
Manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.user.alarm_test">
<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=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" android:enabled="true">
</receiver>
</application>
</manifest>
Activity code:
public class MyActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
start();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancel();
}
});
}
public void start() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 5000;
//schedule alarm to fire every 5 seconds
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis()+interval, interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancel() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
Alarm receiver:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
UPD:I found manager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis()+interval, interval, pendingIntent);
(RTC instead of ELAPSED_REALTIME_WAKEUP) works better but now it calls onReceive only one time.
Upvotes: 1
Views: 269
Reputation: 695
My fault android won't let creating alarm events less often than one per 60 seconds.So I just needed to wait some time.
Upvotes: 0