サイト参考に下記のようにコードを書いてみたのですが通知が表示されません。
何か間違っている箇所ありますでしょうか?
どうかご教授よろしくお願いします。
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import java.util.Calendar; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND,1); scheduleNotification("通知",calendar); } private void scheduleNotification(String content, Calendar calendar){ Intent notificationIntent = new Intent(this, AlarmReceiver.class); notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, 1); notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_CONTENT, content); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } }
import android.app.Notification; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class AlarmReceiver extends BroadcastReceiver { public static String NOTIFICATION_ID = "notificationId"; public static String NOTIFICATION_CONTENT = "content"; @Override public void onReceive(Context context, Intent intent) { NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); int id = intent.getIntExtra(NOTIFICATION_ID, 0); String content = intent.getStringExtra(NOTIFICATION_CONTENT); notificationManager.notify(id, buildNotification(context, content)); } private Notification buildNotification(Context context, String content) { Notification.Builder builder = new Notification.Builder(context); builder.setContentTitle("Notification!!") .setContentText(content) .setSmallIcon(android.R.drawable.sym_def_app_icon); return builder.build(); } }