Попробуйте это,
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private AlarmManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Retrieve a PendingIntent that will perform a broadcast
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
}
public void startAlarm(View view) {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 3000; // 3 seconds
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Log.e("System.currentTime", "" + System.currentTimeMillis());
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(View view) {
if (manager != null) {
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
}
}
и это ваш AlarmReceiver
/**
* Created by Techno Blogger on 1/2/17.
*/
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
}
}
и не забудьте упомянуть об этом в своем Manifest.xml
<receiver android:name=".AlarmReceiver"></receiver>