Androidアプリ(Java)

ポートフォリオ用に
「チャイムアプリ」

MainActivity.java

package com.example.chime01;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.DialogFragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.app.TimePickerDialog;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.TimePicker;

import android.text.format.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.ToggleButton;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;


public class MainActivity extends FragmentActivity
       implements TimePickerDialog.OnTimeSetListener,Interface {

   private WakeLock wakelock;
   private TextView textView;
   ToggleButton tb0;
   TextView tv0;

   String textViewId = "";
   String comment = "";

   TextView[][] txts;
   int[][] txtList = new int[][]{
           {R.id.textView10,R.id.textView11},
           {R.id.textView20,R.id.textView21},
           {R.id.textView30,R.id.textView31},
           {R.id.textView40,R.id.textView41},
           {R.id.textView50,R.id.textView51},
           {R.id.textView60,R.id.textView61},
   };

   String[][] txtIdList = new String[][]{
           {"'textView10'","'textView11'"},
           {"'textView20'","'textView21'"},
           {"'textView30'","'textView31'"},
           {"'textView40'","'textView41'"},
           {"'textView50'","'textView51'"},
           {"'textView60'","'textView61'"},
   };


   ToggleButton[] tgls;
   int[] tglList = new int[]{
           R.id.toggleButton0,
           R.id.toggleButton1,
           R.id.toggleButton2,
           R.id.toggleButton3,
           R.id.toggleButton4,
           R.id.toggleButton5,
           R.id.toggleButton6
   };

   String[] tglIdList = new String[]{
           "'toggleButton0'",
           "'toggleButton1'",
           "'toggleButton2'",
           "'toggleButton3'",
           "'toggleButton4'",
           "'toggleButton5'",
           "'toggleButton6'"
   };

   //アラームの時間保存に使用
   private SetTimeOpenHelper timehelper;
   private SQLiteDatabase db;
   BroadcastReceiver receiver;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       //onCreateに記述しないとヌルポで起動しない
       Typeface font = Typeface.createFromAsset(this.getAssets(), "fontawesome5_free_solid_900.otf");

       //各ボタンにonClickListenerを設定
       final Button button10 = findViewById(R.id.button10);
       button10.setOnClickListener(buttonClick);
       final Button button11 = findViewById(R.id.button11);
       button11.setOnClickListener(buttonClick);

       final Button button20 = findViewById(R.id.button20);
       button20.setOnClickListener(buttonClick);
       final Button button21 = findViewById(R.id.button21);
       button21.setOnClickListener(buttonClick);

       final Button button30 = findViewById(R.id.button30);
       button30.setOnClickListener(buttonClick);
       final Button button31 = findViewById(R.id.button31);
       button31.setOnClickListener(buttonClick);

       final Button button40 = findViewById(R.id.button40);
       button40.setOnClickListener(buttonClick);
       final Button button41 = findViewById(R.id.button41);
       button41.setOnClickListener(buttonClick);

       final Button button50 = findViewById(R.id.button50);
       button50.setOnClickListener(buttonClick);
       final Button button51 = findViewById(R.id.button51);
       button51.setOnClickListener(buttonClick);

       final Button button60 = findViewById(R.id.button60);
       button60.setOnClickListener(buttonClick);
       final Button button61 = findViewById(R.id.button61);
       button61.setOnClickListener(buttonClick);

       /*TextView currentTimeText = (TextView)findViewById(R.id.currentTime);
       Time time = new Time("Asia/Tokyo");
       time.setToNow();
       String date = time.hour + ":" + time.minute + ":" + time.second ;
       currentTimeText.setText(date);*/

       readData();
       for (int value : tglList) {
           tb0 = findViewById(value);
           tb0.setTypeface(font);
           tb0.setOnCheckedChangeListener(CheckedChange);
       }
       tv0 = findViewById(R.id.nextText);
       tv0.setTypeface(font);

       // "com.example.chime01.MY_ALARM_ACTION"を受信するレシーバを登録する
       IntentFilter filter = new IntentFilter("com.example.chime01.MY_ALARM_ACTION");
       //filter.addAction("MyAlarmAction");
       receiver = new BroadcastReceiver() {
           @Override
           public void onReceive(Context context, Intent intent) {
               // ACTION_TIME_TICKを受信したら、TextViewに時刻を表示する
               Log.d("registerReceiver", "受信したよ");
               setChime(0);
               setNext();
           }
       };
       // 署名パーミッションを指定

       this.registerReceiver(receiver, filter, "com.example.chime01.permission.MY_ALARM_BROADCAST", null);
       Log.d("registerReceiver","filter="+filter);
       Log.d("registerReceiver", String.valueOf(registerReceiver(receiver, filter)));

       setNext();

   }
   @SuppressLint("InvalidWakeLockTag")
   @Override
   public void onStart() {
       super.onStart();
       // スリープ状態から復帰する
       wakelock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
               .newWakeLock(PowerManager.FULL_WAKE_LOCK
                       | PowerManager.ACQUIRE_CAUSES_WAKEUP
                       | PowerManager.ON_AFTER_RELEASE, "disableLock");
       wakelock.acquire();

       setChime(0);
       setNext();
       //wakelock.release();
   }

   @Override
   public void onDestroy() {
       super.onDestroy();
       unregisterReceiver(receiver);
       //stopAndRelaese();
       //returnMain();
   }

   public void WLRelease(){
       if(wakelock.isHeld()) {

           wakelock.release();
           Log.d("WLRelease", "WakeLock リリース完了");
       }
   }
   @Override
   //タイムピッカーダイアログで時間が指定されたときの処理
   public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

       String str = String.format(Locale.US, "%02d:%02d", hourOfDay, minute);
       //textView = findViewById(R.id.textViewId);
       textView.setText( str );

       //textViewの更新に併せてDBも更新(or追加)
       Log.d("onSetTime()", String.valueOf(textView));

       //int strId = getResources().getIdentifier(String.valueOf(textViewId), "string", getPackageName());

       //Log.d("onSetTime()", String.valueOf(strId));


       //String viewId = String.valueOf(textView.getId());
       Cursor ch = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;", new String[]{textViewId});

       boolean next = ch.moveToFirst();

       Log.d("debug", String.valueOf(next));
       Log.d("debug_viewId", textViewId);
       //SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");

       if(next){
           changeData(db, textViewId, str, hourOfDay, minute, comment);
       }else {
           insertData(db, textViewId, str, hourOfDay, minute, comment);
       }
       //ch.moveToFirst();
       ch.close();
       setChime(0);
       setNext();
   }
   public void setNext(){
       Cursor nxtchset = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;", new String[]{"'nextChime'"});
       TextView txtNext = findViewById(R.id.nextChimeText);
       TextView txtNextTime = findViewById(R.id.nextChimeTime);
       boolean nxtchnext = nxtchset.moveToFirst();
       if(nxtchnext){
           //columnIndex= 0:id, 1:textViewId, 2:setTime, 3:hour, 4:minute, 5:comment
           String strSetTime = nxtchset.getString(2);
           String strComment = nxtchset.getString(5);

           txtNext.setText(strComment);
           txtNextTime.setText(strSetTime);
       }else {
           txtNext.setText("未設定:");
           txtNextTime.setText("--:--");
       }
       nxtchset.close();


   }

   public void setChime(int addDate){
       //アラームを一旦解除
       MyAlarmManager mam = new MyAlarmManager(this);
       mam.canselAlarm();

       boolean passchecktoggle = false;
       boolean passchecktime = false;
       Log.d("debug_Alarm", "***********Set Chime");
       //readData();
       //ToggleButton toggleButton = findViewById(R.id.toggleButton0);
       //boolean checked = toggleButton.isChecked();
       //アクティビティに依存しないようにDBから取得

       Cursor mch = db.rawQuery("SELECT * FROM settoggletable WHERE toggleButtonId = ? LIMIT 1;",new String[]{String.valueOf(tglIdList[0])});
       Log.d("debug_Alarm", "***********mch:"+mch);
       boolean mnext = mch.moveToFirst();
       boolean checked;

       if(mnext) {
           checked = Boolean.parseBoolean(mch.getString(2));
       }else {
           checked = false;
       }
       Log.d("debug_Alarm", "***********Toggle0 Checked:"+checked);
       if(checked){
           //アラームセットの流れ
           //現在時間を取得
           final Calendar now = Calendar.getInstance();
           now.setTimeInMillis(System.currentTimeMillis());
           int hour = now.get(Calendar.HOUR_OF_DAY);
           int minute = now.get(Calendar.MINUTE);

           //比較用の時間を入れる変数
           Calendar tempCal = Calendar.getInstance();
           tempCal.setTimeInMillis(System.currentTimeMillis());
           tempCal.add(Calendar.DATE, addDate);
           //tempCal = now;

           //各校時のトグルをチェックしてONになっていればその時間を取得
           loop: for (int i = 1; i<tglList.length; i++){

               //toggleButton = findViewById(tglList[i]);
               //boolean checkedSub = toggleButton.isChecked();

               //taglIdListの配列でDB検索
               Cursor sch = db.rawQuery("SELECT * FROM settoggletable WHERE toggleButtonId = ? LIMIT 1;",new String[]{ String.valueOf(tglIdList[i]) });
               //レコードの有無を取得
               boolean snext = sch.moveToFirst();
               boolean checkedSub;

               //レコードがあった場合はトグルの状態をDBから取得
               if(snext) {
                   checkedSub = Boolean.parseBoolean(sch.getString(2));
               }else {
                   checkedSub =  false;
               }

               Log.d("debug_Alarm", "***********Toggle"+i+" Checked:"+checkedSub);
               //ONならその時間を取得
               if(checkedSub){
                   passchecktoggle = true;

                   for (int j = 0; j<2; j++) {
                       //ONだったトグルに対応した時間(textViewに表示してある時間)をtxtIdListの配列でDB検索
                       txts[i - 1][j] = findViewById(txtList[i - 1][j]);
                       Cursor ch = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;",new String[]{ String.valueOf(txtIdList[i-1][j]) });
                       boolean next = ch.moveToFirst();
                       Log.d("debug_Alarm", "***********txts"+i+j+" next:"+next);
                       //SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
                       if(next) {
                           passchecktime = true;

                           hour = ch.getInt(3);
                           minute = ch.getInt(4);
                           String content = ch.getString(5);

                           Log.d("debug_Alarm", "calender temp hour:"+hour);
                           Log.d("debug_Alarm", "calender temp hour:"+minute);
                           tempCal.set(Calendar.HOUR_OF_DAY, hour);
                           tempCal.set(Calendar.MINUTE, minute);
                           Log.d("debug_Alarm", "calender:"+now.before(tempCal));
                           //Log.d("debug_Alarm", "calender:"+tempCal);

                           //現在の時間より後の時間が設定されていたらループを抜ける
                           if (now.before(tempCal)) {
                               //MyAlarmManager mam = new MyAlarmManager(this);
                               mam.addAlarm(hour, minute, addDate, content);
                               Log.d("debug_Alarm", "chime set:"+hour+":"+minute);
                               passchecktime = false;

                               //次のチャイムの情報をDBに入れる
                               Cursor nxtch = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;", new String[]{"'nextChime'"});

                               boolean nxtchnext = nxtch.moveToFirst();

                               //SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
                               //columnIndex= 0:id, 1:textViewId, 2:setTime, 3:hour, 4:minute, 5:comment
                               String strSetTime = ch.getString(2);
                               String strComment = ch.getString(5);
                               if(nxtchnext){
                                   changeData(db, "'nextChime'", strSetTime, hour, minute, strComment+":");
                               }else {
                                   insertData(db, "'nextChime'", strSetTime, hour, minute, strComment+":");
                               }
                               //ch.moveToFirst();
                               nxtch.close();

                               break loop;
                           }
                       }

                       ch.close();
                   }

               }

               sch.close();

           }
           //校時のトグルが1つ以上ON(まだメインのトグルはONのループ内にいる)かつ時間が1つ以上設定されているのに
           //全チェックしてアラームがセットされなかった場合は
           //翌日の日付でセットするように日付を増やしてsetChimeのやり直し
           if(passchecktoggle == true && passchecktime == true){
               Log.d("debug_Alarm", "*********************日付を増やしてやり直し");
               setChime(1);
           }else if(passchecktoggle == false){
               //次のチャイムの情報(未設定になった情報)をDBに入れる
               Cursor nxtch = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;", new String[]{"'nextChime'"});
               Log.d("debug_Alarm", "nxtch:"+nxtch);
               boolean nxtchnext = nxtch.moveToFirst();
               Log.d("debug_Alarm", "nxtchnext:"+nxtchnext);
               if(nxtchnext){
                   changeData(db, "'nextChime'", "--:--", -1, -1, "未設定:");
               }else {
                   insertData(db, "'nextChime'", "--:--", -1, -1, "未設定:");
               }
               //ch.moveToFirst();
               nxtch.close();
           }

       }else{
           //次のチャイムの情報(未設定になった情報)をDBに入れる
           Cursor nxtchclr = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;", new String[]{"'nextChime'"});
           Log.d("debug_Alarm 未設定初期化", "nxtchclr:"+nxtchclr);
           boolean nxtchclrnext = nxtchclr.moveToFirst();

           if(nxtchclrnext){
               changeData(db, "'nextChime'", "--:--", -1, -1, "未設定:");
           }else {
               insertData(db, "'nextChime'", "--:--", -1, -1, "未設定:");
           }
           //ch.moveToFirst();
           nxtchclr.close();

       }
       //使い終わったからいったん閉じる
       mch.close();
       WLRelease();

   }


   //タイムピッカーダイアログ表示
   public void showTimePickerDialog(View v) {
       DialogFragment newFragment = new TimePick();
       newFragment.show(getSupportFragmentManager(), "timePicker");

   }

   //トグルの状態が変更されたときにDBのレコードの有無で処理分け
   public void onCheckedSet(String toggleId, String checked){

       //レコードの検索
       Cursor ch = db.rawQuery("SELECT * FROM settoggletable WHERE toggleButtonId = ? LIMIT 1;", new String[]{toggleId});

       //カーソルを最初の行に移動させることでレコードの有無を調べる
       //レコードがない(カーソルが空)時はfalseを返す
       boolean next = ch.moveToFirst();

       Log.d("debug_nextValue", String.valueOf(next));
       Log.d("debug_viewId", toggleId);
       //SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
       if(next){
           //レコードがあるときはDB更新
           changeToggleData(db, toggleId, checked);
       }else {
           //レコードがないときは追加
           insertToggleData(db, toggleId, checked);
       }
       //ch.moveToFirst();
       ch.close();

   }
   private CompoundButton.OnCheckedChangeListener CheckedChange = new CompoundButton.OnCheckedChangeListener() {
       // トグルボタンがクリックされた時のハンドラ
       @Override
       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


                   Log.d("debug",buttonView+"toggleButton0, Perform action on change");
               String toggleButtonId = "";
                   //ToggleButton changedButton = findViewById(R.id.toggleButton0);
                   //String toggleButtonId = String.valueOf(buttonView.getId());
           switch (buttonView.getId()) {
               case R.id.toggleButton0:
                   toggleButtonId = "'toggleButton0'";
                   break;

               case R.id.toggleButton1:
                   toggleButtonId = "'toggleButton1'";
                   break;

               case R.id.toggleButton2:
                   toggleButtonId = "'toggleButton2'";
                   break;

               case R.id.toggleButton3:
                   toggleButtonId = "'toggleButton3'";
                   break;

               case R.id.toggleButton4:
                   toggleButtonId = "'toggleButton4'";
                   break;

               case R.id.toggleButton5:
                   toggleButtonId = "'toggleButton5'";
                   break;

               case R.id.toggleButton6:
                   toggleButtonId = "'toggleButton6'";
                   break;
           }

                   // トグルボタンの状態が変更された時の処理を記述
                   if(isChecked) {
                       Log.v("OnCheckedChanged", "ON");
                       onCheckedSet(toggleButtonId,"true");
                   }else {
                       Log.v("OnCheckedChanged", "OFF");
                       onCheckedSet(toggleButtonId,"false");
                   }
                   //break;
           //}

           setChime(0);
           setNext();
       }

   };

       //ボタンクリックで発火 TimePicker表示
   private View.OnClickListener buttonClick = new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           switch (view.getId()) {
               case R.id.button10:
                   textView = findViewById(R.id.textView10);
                   textViewId = "'textView10'";
                   comment = "1校時 開始";
                   Log.d("debug","button10, Perform action on click");
                   showTimePickerDialog(view);
                   break;
               case R.id.button11:
                   textView = findViewById(R.id.textView11);
                   Log.d("debug","button11, Perform action on click");
                   textViewId = "'textView11'";
                   comment = "1校時 終了";
                   showTimePickerDialog(view);
                   break;

               case R.id.button20:
                   textView = findViewById(R.id.textView20);
                   Log.d("debug","button20, Perform action on click");
                   textViewId = "'textView20'";
                   comment = "2校時 開始";
                   showTimePickerDialog(view);
                   break;
               case R.id.button21:
                   textView = findViewById(R.id.textView21);
                   Log.d("debug","button21, Perform action on click");
                   textViewId = "'textView21'";
                   comment = "2校時 終了";
                   showTimePickerDialog(view);
                   break;

               case R.id.button30:
                   textView = findViewById(R.id.textView30);
                   Log.d("debug","button30, Perform action on click");
                   textViewId = "'textView30'";
                   comment = "3校時 開始";
                   showTimePickerDialog(view);
                   break;
               case R.id.button31:
                   textView = findViewById(R.id.textView31);
                   Log.d("debug","button31, Perform action on click");
                   textViewId = "'textView31'";
                   comment = "3校時 終了";
                   showTimePickerDialog(view);
                   break;

               case R.id.button40:
                   textView = findViewById(R.id.textView40);
                   Log.d("debug","button40, Perform action on click");
                   textViewId = "'textView40'";
                   comment = "4校時 開始";
                   showTimePickerDialog(view);
                   break;
               case R.id.button41:
                   textView = findViewById(R.id.textView41);
                   Log.d("debug","button41, Perform action on click");
                   textViewId = "'textView41'";
                   comment = "4校時 終了";
                   showTimePickerDialog(view);
                   break;

               case R.id.button50:
                   textView = findViewById(R.id.textView50);
                   Log.d("debug","button50, Perform action on click");
                   textViewId = "'textView50'";
                   comment = "5校時 開始";
                   showTimePickerDialog(view);
                   break;
               case R.id.button51:
                   textView = findViewById(R.id.textView51);
                   Log.d("debug","button51, Perform action on click");
                   textViewId = "'textView51'";
                   comment = "5校時 終了";
                   showTimePickerDialog(view);
                   break;

               case R.id.button60:
                   textView = findViewById(R.id.textView60);
                   Log.d("debug","button60, Perform action on click");
                   textViewId = "'textView60'";
                   comment = "6校時 開始";
                   showTimePickerDialog(view);
                   break;
               case R.id.button61:
                   textView = findViewById(R.id.textView61);
                   Log.d("debug","button61, Perform action on click");
                   textViewId = "'textView61'";
                   comment = "6校時 開始";
                   showTimePickerDialog(view);
                   break;
           }
       }
   };

   //DBからデータの読み込み
   public void readData(){
       if(timehelper == null){
           timehelper = new SetTimeOpenHelper(getApplicationContext());
       }

       if(db == null){
           db = timehelper.getReadableDatabase();
       }
       Log.d("debug","**********Cursor");

       //ここでDBから値を取得して cursor に配列で定義してるっぽい
       Cursor cursor = db.query(
               "settimetable",
               new String[] { "textViewId", "setTime", "setComment" },
               null,
               null,
               null,
               null,
               null
       );

       cursor.moveToFirst();

       //StringBuilder sbuilder = new StringBuilder();

       //ここでcursorの値を順に取り出して(moveToNext)sbuilderに追記していってる
       /*for (int i = 0; i < cursor.getCount(); i++) {
           //sbuilder.append(cursor.getInt(0));
           //sbuilder.append(": ");
           sbuilder.append(cursor.getString(1));
           //sbuilder.append("\n");
           cursor.moveToNext();
       }*/

       // 忘れずに!(終わったらcursorを閉じてるんだと思う)
       //cursor.close();

       //Log.d("debug","**********"+sbuilder.toString());

       txts = new TextView[6][2];
       tgls = new ToggleButton[tglList.length];

       //時間のレコードチェック
       for (int i = 0; i<6; i++){
           for (int j = 0; j<2; j++){
               txts[i][j]=findViewById(txtList[i][j]);

               //該当のレコードがあるかチェック
               Cursor ch = db.rawQuery("SELECT * FROM settimetable WHERE textViewId = ? LIMIT 1;",new String[]{ String.valueOf(txtIdList[i][j]) });
               boolean next = ch.moveToFirst();

               //SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
               if(next){

                   //sbuilder.append(cursor.getString(1));

                   //columnIndex= 0:id, 1:textViewId, 2:setTime
                   txts[i][j].setText(ch.getString(2).toString());
                   //Log.d("debug_next:"+String.valueOf(txtList[i][j]),"**********"+sbuilder.toString());
               }else {
                   txts[i][j].setText("--:--");
               }
               //使い終わったからいったん閉じる
               ch.close();
           }
       }

       //トグルボタンのレコードチェック
       for (int i = 0; i<tglList.length; i++){
               tgls[i]=findViewById(tglList[i]);

               //該当のレコードがあるかチェック
               Cursor ch = db.rawQuery("SELECT * FROM settoggletable WHERE toggleButtonId = ? LIMIT 1;",new String[]{ String.valueOf(tglIdList[i]) });
               boolean next = ch.moveToFirst();

               //SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");
               if(next){

                   //sbuilder.append(cursor.getString(1));

                   //columnIndex= 0:id, 1:toggleButtonId, 2:setChecked
                   tgls[i].setChecked(Boolean.parseBoolean(ch.getString(2)));
                   Log.d("debug_next:"+String.valueOf(tglIdList[i]),"**********"+ch.getString(2));
               }else {
                   tgls[i].setChecked(false);
               }
               //使い終わったからいったん閉じる
               ch.close();
       }

       cursor.close();

   }

   //時間データ
   //新規データの追加
   private void insertData(SQLiteDatabase db, String id, String time, int hour, int minute, String comment){

       ContentValues values = new ContentValues();
       values.put("textViewId", id);
       values.put("setTime", time);
       values.put("setHour", hour);
       values.put("setMinute", minute);
       values.put("setComment", comment);
       Log.d("debugT", "insert:" + String.valueOf(values));
       db.insert("settimetable", null, values);
   }

   //データの更新
   private void changeData(SQLiteDatabase db, String id, String time, int hour, int minute, String comment){

       ContentValues values = new ContentValues();
       values.put("textViewId", id);
       values.put("setTime", time);
       values.put("setHour", hour);
       values.put("setMinute", minute);
       values.put("setComment", comment);
       Log.d("debug", "change:" + String.valueOf(values));
       db.update("settimetable", values,"textViewId = ?",new String[]{id});
   }

   //トグルデータ
   //新規データの追加
   private void insertToggleData(SQLiteDatabase db, String id, String checked){

       ContentValues values = new ContentValues();
       values.put("toggleButtonId", id);
       values.put("setChecked", checked);
       Log.d("debugT", "insert:" + String.valueOf(values));
       db.insert("settoggletable", null, values);
   }

   //データの更新
   private void changeToggleData(SQLiteDatabase db, String id, String checked){

       ContentValues values = new ContentValues();
       values.put("toggleButtonId", id);
       values.put("setChecked", checked);
       Log.d("debug", "change:" + String.valueOf(values));
       db.update("settoggletable", values,"toggleButtonId = ?",new String[]{id});
   }

}

MyAlarmManager.java

package com.example.chime01;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import java.util.Calendar;

public class MyAlarmManager {
   Context c;
   AlarmManager am;
   private PendingIntent mAlarmSender;

   public MyAlarmManager(Context c){
       this.c = c;
       am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
       Log.v("MyAlarmManger","初期化完了");
   }

   public void addAlarm(int alarmHour, int alarmMinute, int alarmDate, String content){
       Intent notificationIntent = new Intent(c, MyAlarmService.class);
       Bundle bundle = new Bundle();
       bundle.putString("NOTIFICATION_CONTENT", content);
       notificationIntent.putExtras(bundle);
       Log.v("NOTIFICATION_CONTENT:",notificationIntent.getStringExtra("NOTIFICATION_CONTENT"));
       mAlarmSender = PendingIntent.getService(c, 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
       //mAlarmSender = PendingIntent.getService(c, 1, new Intent(c, MyAlarmService.class), PendingIntent.FLAG_UPDATE_CURRENT);
       am.cancel(mAlarmSender);

       // アラーム時間設定
       Calendar cal = Calendar.getInstance();
       cal.setTimeInMillis(System.currentTimeMillis());
       cal.add(Calendar.DATE, alarmDate);
       cal.set(Calendar.HOUR_OF_DAY, alarmHour);
       cal.set(Calendar.MINUTE, alarmMinute);
       cal.set(Calendar.SECOND, 0);
       cal.set(Calendar.MILLISECOND, 0);
       Log.v("MyAlarmManagerログ",cal.getTimeInMillis()+"ms");
       Log.v("MyAlarmManagerログ",cal+"cal");
       if (Build.VERSION.SDK_INT < 21) {
           if (Build.VERSION.SDK_INT >= 19) {
               am.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), mAlarmSender);
           } else {
               am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), mAlarmSender);
           }
       } else {
           am.setAlarmClock(new AlarmManager.AlarmClockInfo(cal.getTimeInMillis(),mAlarmSender), mAlarmSender);
       }
       Log.v("MyAlarmManagerログ","アラームセット完了");
   }

   public void canselAlarm(){
       mAlarmSender = PendingIntent.getService(c, 1, new Intent(c, MyAlarmService.class), PendingIntent.FLAG_UPDATE_CURRENT);
       am.cancel(mAlarmSender);
       Log.v("MyAlarmManger","アラーム解除完了");
   }
}

SetTimeOpenHelper.java

package com.example.chime01;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SetTimeOpenHelper extends SQLiteOpenHelper {

   // データーベースのバージョン
   private static final int DATABASE_VERSION = 1;

   // データーベース名
   private static final String DATABASE_NAME = "SetChimeDB.db";
   //時間を入れるテーブル
   private static final String TABLE_NAME_SETTIME = "settimetable";
   private static final String _ID = "_id";
   private static final String COLUMN_NAME_TEXTVIEWID = "textViewId";
   private static final String COLUMN_NAME_SETTIME = "setTime";
   private static final String COLUMN_NAME_SETHOUR = "setHour";
   private static final String COLUMN_NAME_SETMINUTE = "setMinute";
   private static final String COLUMN_NAME_COMMENT = "setComment";

   private static final String SQL_CREATE_ENTRIES_SETTIME =
           "CREATE TABLE " + TABLE_NAME_SETTIME + " (" +
                   _ID + " INTEGER PRIMARY KEY," +
                   COLUMN_NAME_TEXTVIEWID + " TEXT," +
                   COLUMN_NAME_SETTIME + " TEXT," +
                   COLUMN_NAME_SETHOUR + " INTEGER," +
                   COLUMN_NAME_SETMINUTE + " INTEGER," +
                   COLUMN_NAME_COMMENT + " TEXT)";

   private static final String SQL_DELETE_ENTRIES_SETTIME =
           "DROP TABLE IF EXISTS " + TABLE_NAME_SETTIME;

   //トグルの状態を保存するテーブル
   private static final String TABLE_NAME_SETTOGGLE = "settoggletable";
   private static final String COLUMN_NAME_TOGGLEBUTTONID = "toggleButtonId";
   private static final String COLUMN_NAME_SETCHECKED = "setChecked";

   private static final String SQL_CREATE_ENTRIES_SETTOGGLE =
           "CREATE TABLE " + TABLE_NAME_SETTOGGLE + " (" +
                   _ID + " INTEGER PRIMARY KEY," +
                   COLUMN_NAME_TOGGLEBUTTONID + " TEXT," +
                   COLUMN_NAME_SETCHECKED + " INTEGER)";

   private static final String SQL_DELETE_ENTRIES_SETTOGGLE =
           "DROP TABLE IF EXISTS " + TABLE_NAME_SETTOGGLE;

   SetTimeOpenHelper(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);

   }

   @Override
   public void onCreate(SQLiteDatabase db) {

       // テーブル作成
       // SQLiteファイルがなければSQLiteファイルが作成される
       db.execSQL(
               SQL_CREATE_ENTRIES_SETTIME
       );
       db.execSQL(
               SQL_CREATE_ENTRIES_SETTOGGLE
       );

       Log.d("debug", "onCreate(SQLiteDatabase db)");

   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       // アップデートの判別
       db.execSQL(
               SQL_DELETE_ENTRIES_SETTIME
       );

       db.execSQL(
               SQL_DELETE_ENTRIES_SETTOGGLE
       );
       onCreate(db);
   }

   public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       onUpgrade(db, oldVersion, newVersion);
   }


}

MyAlarmNotificationReceiver.java

package com.example.chime01;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class MyAlarmNotificationReceiver extends BroadcastReceiver implements MediaPlayer.OnCompletionListener {

   MediaPlayer mp = null;
   private MainActivity instanceMainActivity;

   /*public MyAlarmNotificationReceiver() {
       this.instanceMainActivity = new MainActivity();
   }*/

   @Override
   public void onReceive(Context context, Intent intent) {

       switch (intent.getAction()) {
           case "com.example.chime01.MY_ALARM_ACTION":
               // ここで受信したブロードキャストに対する処理を実行

               Log.v("レシーバログ", "action: " + intent.getAction());

               // 通知を作成するビルダーの生成(チャンネルIDの指定)
               final String CHANNEL_ID = String.valueOf(R.string.notification_channel_id);
               NotificationCompat.Builder builder;
               if (Build.VERSION.SDK_INT <= 25) {
                   builder = new NotificationCompat.Builder(context);
               }else {
                   builder = new NotificationCompat.Builder(context, CHANNEL_ID);
               }

               builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

               // 通知のアイコン
               builder.setSmallIcon(R.drawable.ic_action_time_of_chime);

               // 通知のタイトル
               builder.setContentTitle("チャイムの時間");

               // 通知の内容
               String content = intent.getStringExtra("NOTIFICATION_CONTENT");
               builder.setContentText(content);

               // 通知をタップした際にアクティビティを起動する
               // --- ここを削除すると通知の表示のみとなる
               Intent intentMainActivity = new Intent(context,MainActivity.class);
               intentMainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
               //intentMainActivity.putExtra("DATA","通知から起動されました。");

               PendingIntent pen = PendingIntent.getActivity(context,
                       232743001, // 0は識別子。何でも良い
                       intentMainActivity,
                       PendingIntent.FLAG_CANCEL_CURRENT);  // オブジェクトを再生成
               builder.setContentIntent(pen);
               builder.setAutoCancel(true);
               // --- ここを削除すると通知の表示のみとなる

               // 通知の作成
               Notification notification = builder.build();
               Log.v("レシーバログ", "notification: " + notification);
               // 通知サービスで通知を実行する
               //NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
               NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
               notificationManager.notify(228776001, notification); // 0は識別子。何でも良い

               Intent notificationActivity = new Intent(context,
                       MainActivity.class);
               //ここがないと画面を起動できません
               notificationActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                       | Intent.FLAG_ACTIVITY_NO_ANIMATION
                       | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT

               );
               //notificationActivity.putExtra("MEDIAPLAYER", (Parcelable) mp);

               context.startActivity(notificationActivity);

               if (mp == null)
                   mp = MediaPlayer.create(context, R.raw.bell02);
               mp.start();
               mp.setOnCompletionListener(this);

               //setChime(0);
               break;

       }

   }

   @Override
   public void onCompletion(MediaPlayer mp) {
       Log.v("MediaPlayer", "onCompletion");
       // ここに再生完了時の処理を追加
       //onDestroy();
       stopAndRelaese();
       //WLRelease();
   }

   private void stopAndRelaese() {
       if (mp != null) {
           Log.v("MediaPlayer", "*****STOP*****mp:"+mp);
           mp.stop();
           mp.reset();
           mp.release();
           mp = null;
       }
   }

/*
   public void setChime(int addDate) {
       this.instanceMainActivity.setChime(addDate);
   }

   public void WLRelease() {
       this.instanceMainActivity.WLRelease();
   }
*/

}


いいなと思ったら応援しよう!