指定した時間にWebApiをたたいて、情報(JSON)を取得したい
お世話になります。
AndroidStudioではじめてのアンドロイドアプリ開発を行っています。
掲題の件でお力添えいただきたいです。
ボタンを押された際にアラームをセットして、指定時間(ここでは10時00分00秒)に端末に通知を送るという処理はかけました。
現在やりたいことはAlarmReceiver2クラスのonReceiveメソッドでWebApiをたたき、その結果を判定して、通知する・しないを分けることです。
イメージは下記になります。
Java
1 public void onReceive(Context context, Intent intent) { 2 3 //ここでWebApiをたたいて情報を取得したい 4 result = getMovieTitle(); 5 6 if(result == "Your Name."){ 7 //通知処理 8 Notification( context, intent); 9 } 10 }
このサイトを参考にして、あるボタンを押した際のJSONの取得および画面への表示はできましたが、
AppCompatActivityを継承していないクラスでWebApiをたたく方法がわかりません。
アプリが起動中でない時に掲題の処理を行うことを想定しており、「Android WebApi」などで検索しましたが、なかなかほしい情報が得られませんでした。
学習を主の目的としているため、「考え方」や「検索ワード」などを教えていただけるだけでも大変ありがたいです。
初学者につき、とんちんかんな質問をしているかもしれませんが、なにとぞよろしくお願いいたします。
該当のソースコード
Kotlin
1 // 実行する時間 2 var calendar : Calendar = Calendar.getInstance() 3 calendar.set(Calendar.HOUR,10) 4 calendar.set(Calendar.MINUTE,0) 5 calendar.set(Calendar.SECOND,0) 6 // 実行したいクラスから Intent を作成 7 val alarmIntent = Intent(this, AlarmReceiver2::class.java) 8 val pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT) 9 10 // AlarmManager で pendingIntent を指定時間後に実行するように設定 11 val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager 12 manager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent); 13
Java
1public class AlarmReceiver2 extends BroadcastReceiver { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 //通知処理 5 Notification( context, intent); 6 } 7 8 public void Notification(Context context, Intent intent){ 9 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 10 String channelId = "updates"; // 通知チャンネルのIDにする任意の文字列 11 String name = "更新情報"; // 通知チャンネル名 12 int importance = NotificationManager.IMPORTANCE_HIGH; // デフォルトの重要度 13 NotificationChannel channel = new NotificationChannel(channelId, name, importance); 14 channel.setDescription("通知チャンネルの説明"); // 必須ではない 15 16 // 通知チャンネルの設定のデフォルト値。設定必須ではなく、ユーザーが変更可能。 17 channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); 18 channel.enableVibration(true); 19 channel.enableLights(true); 20 channel.setShowBadge(false); // ランチャー上でアイコンバッジを表示するかどうか 21 22 // NotificationManagerCompatにcreateNotificationChannel()は無い。 23 NotificationManager nm = getSystemService(context , NotificationManager.class); 24 nm.createNotificationChannel(channel); 25 26 // 通知チャンネルのIDを指定するコンストラクタが増えている 27 NotificationCompat.Builder builder 28 = new NotificationCompat.Builder(context, channelId) 29 .setContentTitle("TEST_Title") 30 .setContentText("TEST_Text") 31 .setSmallIcon(R.drawable.sample); 32 NotificationManagerCompat.from(context).notify(1, builder.build()); 33 } 34 } 35}
JSON
1{ 2 "movies": [ 3 { 4 "title": "Your Name.", 5 "year": 2016 6 } 7 ] 8}
補足情報(FW/ツールのバージョンなど)
AndroidStudio3.4
Java
Kotlin
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。