Gece ikiden bu yana test uygulamasına anlık bildirim gönderme özelliği üzerinde çalışıyorum. Sonunda zamana dayalı ve arkaplanda uygulama kapansa dahi çalışmaya devam edecek anlık bildirim gönderme özelliğini ekledim. Şimdi sırayla o adımlar:
AndroidManifext.xml
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<receiver android:name=".MainActivity$BgNotifProReceiver" android:exported="false" />
<receiver android:name=".Bildirimler" android:exported="false" />
package com.beta;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import java.io.InputStream;
import java.net.URL;
public class Bildirimler extends BroadcastReceiver {
@Override
public void onReceive(final Context _ctx, final Intent _intent) {
new Thread(new Runnable() {
@Override
public void run() {
int _id = _intent.getIntExtra("id", 1);
String _title = _intent.getStringExtra("title");
String _text = _intent.getStringExtra("text");
String _chName = _intent.getStringExtra("channel");
String _iconName = _intent.getStringExtra("icon");
String _colorHex = _intent.getStringExtra("color");
String _bigImg = _intent.getStringExtra("bigImg");
String _soundName = _intent.getStringExtra("sound");
if (_title == null) _title = "Bildirimler";
if (_text == null) _text = "";
if (_chName == null) _chName = "Bildirimler";
String _chId = (_soundName != null && !_soundName.isEmpty()) ? "sw_bg_pro_" + _soundName : "sw_bg_pro_default";
Uri _soundUri = null;
if (_soundName != null && !_soundName.isEmpty()) {
int _sRes = _ctx.getResources().getIdentifier(_soundName, "raw", _ctx.getPackageName());
if (_sRes != 0) {
_soundUri = Uri.parse("android.resource://" + _ctx.getPackageName() + "/" + _sRes);
}
}
int _iconRes = _ctx.getApplicationInfo().icon;
if (_iconName != null && !_iconName.isEmpty()) {
int _res = _ctx.getResources().getIdentifier(_iconName, "drawable", _ctx.getPackageName());
if (_res != 0) _iconRes = _res;
}
NotificationManager _nm = (NotificationManager) _ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel _ch = new NotificationChannel(_chId, _chName, NotificationManager.IMPORTANCE_HIGH);
if (_soundUri != null) {
AudioAttributes _aa = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
_ch.setSound(_soundUri, _aa);
}
_nm.createNotificationChannel(_ch);
Intent _openIntent = new Intent(_ctx, MainActivity.class);
_openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int _pFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
_pFlags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent _contentPi = PendingIntent.getActivity(_ctx, _id, _openIntent, _pFlags);
Notification.Builder _builder = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
? new Notification.Builder(_ctx, _chId)
: new Notification.Builder(_ctx);
_builder.setSmallIcon(_iconRes)
.setContentTitle(_title)
.setContentText(_text)
.setContentIntent(_contentPi)
.setAutoCancel(true);
if (_soundUri != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
_builder.setSound(_soundUri);
}
if (_colorHex != null && !_colorHex.isEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
_builder.setColor(Color.parseColor(_colorHex));
} catch (Exception _e) {}
}
if (_bigImg != null && !_bigImg.isEmpty()) {
Bitmap _bmp = null;
if (_bigImg.startsWith("http://") || _bigImg.startsWith("https://")) {
try {
InputStream _in = new URL(_bigImg).openStream();
_bmp = BitmapFactory.decodeStream(_in);
_in.close();
} catch (Exception _e) {}
} else {
int _imgRes = _ctx.getResources().getIdentifier(_bigImg, "drawable", _ctx.getPackageName());
if (_imgRes != 0) {
_bmp = BitmapFactory.decodeResource(_ctx.getResources(), _imgRes);
}
}
if (_bmp != null) {
_builder.setLargeIcon(_bmp);
_builder.setStyle(new Notification.BigPictureStyle().bigPicture(_bmp));
}
}
_nm.notify(_id, _builder.build());
}
}).start();
}
}
{
final int _hour = (int) (Double.parseDouble(edittext1.getText().toString()));
final int _minute = (int) (Double.parseDouble(edittext2.getText().toString()));
final int _notifId = (int) (1);
java.util.Calendar _cal = java.util.Calendar.getInstance();
_cal.set(java.util.Calendar.HOUR_OF_DAY, _hour);
_cal.set(java.util.Calendar.MINUTE, _minute);
_cal.set(java.util.Calendar.SECOND, 0);
_cal.set(java.util.Calendar.MILLISECOND, 0);
if (_cal.getTimeInMillis() <= System.currentTimeMillis()) {
_cal.add(java.util.Calendar.DAY_OF_YEAR, 1);
}
android.content.Intent _intent = new android.content.Intent(getApplicationContext(), Bildirimler.class);
_intent.putExtra("id", _notifId);
_intent.putExtra("title", edittext3.getText().toString());
_intent.putExtra("text", edittext4.getText().toString());
_intent.putExtra("channel", "push");
_intent.putExtra("icon", "bakery");
_intent.putExtra("color", "#926C25");
_intent.putExtra("bigImg", "");
_intent.putExtra("sound", "bildirim");
int _flags = android.app.PendingIntent.FLAG_UPDATE_CURRENT;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
_flags |= android.app.PendingIntent.FLAG_IMMUTABLE;
}
android.app.PendingIntent _pi = android.app.PendingIntent.getBroadcast(getApplicationContext(), _notifId, _intent, _flags);
android.app.AlarmManager _am = (android.app.AlarmManager) getSystemService(android.content.Context.ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 31) {
if (_am.canScheduleExactAlarms()) {
_am.setExactAndAllowWhileIdle(android.app.AlarmManager.RTC_WAKEUP, _cal.getTimeInMillis(), _pi);
} else {
_am.setAndAllowWhileIdle(android.app.AlarmManager.RTC_WAKEUP, _cal.getTimeInMillis(), _pi);
}
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
_am.setExactAndAllowWhileIdle(android.app.AlarmManager.RTC_WAKEUP, _cal.getTimeInMillis(), _pi);
} else {
_am.setExact(android.app.AlarmManager.RTC_WAKEUP, _cal.getTimeInMillis(), _pi);
}
}if (android.os.Build.VERSION.SDK_INT >= 33) {
if (checkSelfPermission("android.permission.POST_NOTIFICATIONS") != android.content.pm.PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, 101);
}
}Şimdi yazdığımızı okuyalım yahut da anlatalım. İlk olarak AndroidManifext.xml dosyasına izinleri tanımladık. Bu izinler telefonunuzun Ayarlar > Uygulama bilgileri kısmında büyük bir çoğunluğunu kontrol edebildiğiniz İzinler kısmıdır. Bu izinler olmadan diğer kısımlarda yaptığınızın hiç bir önemi yok. Yani bu dosya bir nevi evinizin cümle kapısı. Bu kapı kapalı olursa misafir eve giremdikten sonra odaların güzelliğinin bir önemi yok.
Aynı dosya içinde birde <receiver .... /> kısmı var. Bu kod arkaplanda çalışan servisleri kontrol eder. Yani herhangi bir uygulamayı decompile edip (tersine mühendislik) AndroidManifext.xml dosyasındaki bu kodları yani <receiver /> kodlarını silseniz bildirimler falan gelmez. Verileriniz otomatik yedeklenmez vesaire vesaire. AndroidManifext.xml dosyası hakkında ek bilgi vereyim. Bu dosyanın içinde uygulamalarda gösterilen reklamları tanımlı olduğu kod satırını silerseniz uygulamada reklam görmezsiniz. Önceden Apk Editör Pro diye bir uygulama vardı eski telefonumda yapıyordum.
Gelelim Bildirimler.java kısmına. Aslında bu kod MainActivity.java daki kodun arkaplanda çalışması için ek bir tembih gibi bir şey sey. Nöbetteki asker misali. İşte diyorsunuz ki her gün saat 7 de kırmızı arama yoldan geçiyor mu? Eğer geçiyorsa şunu şunu yap. Bunun gibi. Benim yazdığım kodda ise MainActivity.java'da input kısımları var. Bu imputlardaki verileri şu saat ve dakika geldiğinde bana bildirim gönder. Koca java kodunun özeti bu.
MainActivity.java > Buton Clicker
Bu kod da inputtaki verileri bir kağıda yazar gibi bir anahtar kelimeyle kaydedip Bildirimler kısmına gönderiyorsunuz. Bildirimler kısmı verileri kıyas edip varsa gereken görevi yerine getiriyor. Bunu da betimleyelim. Siz bir komutansınız nöbetteki askerinize elinizde şu eşgallere uyan insanları tutuklayın demek gibi bir şey.
MainActivity.java > OnCreate
Bu da anne ben çarşıya gidebilir miyim diye izin isteyen bir çocuk kodu. Başlangıçta soruyor Bildirim gönderme me izin veriyor musun? diye. Eğer evet derseniz bildirim düşüyor yok hayır derseniz bildirim görmüyorsunuz.
Ne yalan söyleyeyim şunları yaparken beynimin pancar motoru gibi çalıştığını hissediyorum. Kafamdan dumanlar çıkıyor ama bi o kadar da keyif bee. Acayip bir şey. Uzun bir aradan sonra böyle uzun bir yazı yazmak da bir hoşuma gitti. Bunları daha mı sık yapsam. Neyse işte öyle.