Android Alarm Manager Kullanımı

AndroidManifest.xml dosyasına application tag'i içerisine ekleyiniz;

<receiver android:name=".AlarmReceiver"></receiver>

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null)
        {
            alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    AlarmManager alarmMgr;
    PendingIntent pendingIntent;

    public void startAlarmManager()
    {
        Intent dialogIntent = new Intent(getBaseContext(), AlarmReceiver.class);

        alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        pendingIntent = PendingIntent.getBroadcast(this, 0, dialogIntent,PendingIntent.FLAG_CANCEL_CURRENT);

        alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 3000, pendingIntent);

    }
    public void stopAlarmManager()
    {
        if(alarmMgr != null)
            alarmMgr.cancel(pendingIntent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startAlarmManager();
        //stopAlarmManager();
    }
}
Bu makaleyi paylaşın:

3 Comments

Bir yorum bırakın