diff --git a/.idea/misc.xml b/.idea/misc.xml index 0ad17cb..8978d23 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,3 @@ - diff --git a/app/src/main/java/com/example/childguard/HomeFragment.java b/app/src/main/java/com/example/childguard/HomeFragment.java index a9358b0..59efc75 100644 --- a/app/src/main/java/com/example/childguard/HomeFragment.java +++ b/app/src/main/java/com/example/childguard/HomeFragment.java @@ -110,7 +110,7 @@ public class HomeFragment extends Fragment implements OnEventListener{ transaction.commit(); } - private boolean updateUiState(boolean state) { + private boolean updateUiState(boolean isInCar) { Log.d("HomeFragment", "updateUiState: called"); // Init TextView tv; @@ -123,13 +123,13 @@ public class HomeFragment extends Fragment implements OnEventListener{ return false; } catch (IllegalStateException e) { Log.d("HomeFragment", "updateUiState: view is not attached"); -// getParentFragmentManager().beginTransaction().replace(R.id.fragmentContainerView, HomeFragment.newInstance("test", "test")).commit(); -// updateUiState(state); + getParentFragmentManager().beginTransaction().replace(R.id.fragmentContainerView, HomeFragment.newInstance("test", "test")).commit(); + updateUiState(isInCar); return false; } String get_on = "\n乗車状態"; String get_off = "\n降車状態"; - if (state) { + if (!isInCar) { //乗車状態にする fl.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.frame_style_orange, null)); tv.setText(get_on); @@ -143,9 +143,10 @@ public class HomeFragment extends Fragment implements OnEventListener{ } @Override - public boolean onEvent(boolean state) { + public boolean onEvent(boolean isInCar) { Log.d("HomeFragment", "onEvent: called"); - return updateUiState(state); + + return updateUiState(isInCar); } } diff --git a/app/src/main/java/com/example/childguard/MainActivity.java b/app/src/main/java/com/example/childguard/MainActivity.java index 797253a..3379dbd 100644 --- a/app/src/main/java/com/example/childguard/MainActivity.java +++ b/app/src/main/java/com/example/childguard/MainActivity.java @@ -1,15 +1,5 @@ package com.example.childguard; -import static java.security.AccessController.getContext; - -import androidx.activity.result.ActivityResultLauncher; -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.app.AppCompatActivity; -import androidx.browser.customtabs.CustomTabsIntent; -import androidx.core.app.ActivityCompat; -import androidx.core.app.NotificationCompat; -import androidx.core.app.NotificationManagerCompat; - import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; @@ -18,50 +8,49 @@ import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.Context; -import android.content.SharedPreferences; import android.content.Intent; import android.content.IntentFilter; +import android.content.SharedPreferences; import android.content.pm.PackageManager; -import android.graphics.Color; -import android.graphics.Paint; import android.net.Uri; import android.os.Bundle; import android.os.Vibrator; - -import com.google.android.material.bottomnavigation.BottomNavigationView; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Random; -import java.util.UUID; - import android.preference.PreferenceManager; import android.util.Log; import android.widget.FrameLayout; -import android.widget.TextView; import android.widget.Toast; + +import androidx.activity.result.ActivityResultLauncher; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; -import androidx.core.content.res.ResourcesCompat; -import androidx.core.graphics.Insets; -import androidx.core.view.ViewCompat; -import androidx.core.view.WindowInsetsCompat; +import androidx.browser.customtabs.CustomTabsIntent; +import androidx.core.app.ActivityCompat; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; +import com.google.android.gms.tasks.OnFailureListener; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; -import com.google.zxing.integration.android.IntentIntegrator; -import com.google.zxing.integration.android.IntentResult; import com.journeyapps.barcodescanner.ScanContract; import com.journeyapps.barcodescanner.ScanOptions; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Future; + public class MainActivity extends AppCompatActivity { + FirebaseFirestore db; BluetoothManager bluetoothManager; BluetoothAdapter bluetoothAdapter; @@ -71,14 +60,8 @@ public class MainActivity extends AppCompatActivity { public static final String TAG = "InspirationQuote"; - boolean flg = false; - //↓日付を取得するやつ - public static String getNowDate() { - @SuppressLint("SimpleDateFormat") final DateFormat df = new SimpleDateFormat("yyy/MM/dd HH:mm:ss"); - final Date date = new Date(System.currentTimeMillis()); - return df.format(date); - } + private final ActivityResultLauncher QrLauncher = registerForActivityResult( new ScanContract(), @@ -105,7 +88,7 @@ public class MainActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); -// super.onStart(); + db = FirebaseFirestore.getInstance();//Firebaseとの紐づけ BottomNavigationView bottomNavigationView = findViewById(R.id.nav_view); @@ -170,55 +153,50 @@ public class MainActivity extends AppCompatActivity { if (IdPref == null) { Log.d("onResume", "ID not initialized."); } else { - mDocRef = FirebaseFirestore.getInstance().document("users/" + IdPref);//現在の位置を取得 - this.flg = false; + mDocRef = FirebaseFirestore.getInstance().document("status/" + IdPref);//現在の位置を取得 initNotification(mDocRef); } } private void initNotification(DocumentReference mDocRef) { - // Init pref SharedPreferences sharedPreferences = getSharedPreferences("app_situation",MODE_PRIVATE); mDocRef.addSnapshotListener(this, new EventListener() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { + Log.d("nt", "イベント開始"); //共有プリファレンス 書き込みの準備 - SharedPreferences.Editor E=sharedPreferences.edit(); + SharedPreferences.Editor E = sharedPreferences.edit(); //車の乗り降りを管理するtrue=乗車、false=降車 - boolean isInCar = sharedPreferences.getBoolean("car", false); - if (flg && documentSnapshot != null && documentSnapshot.exists()) { - - String parent = documentSnapshot.getString("parent"); + if (documentSnapshot.exists()) { + Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView); + Boolean isInCar = sharedPreferences.getBoolean("isInCarPref", false);//現在の乗降状態を保存する共有プリファレンス + E.putBoolean("isInCarPref", documentSnapshot.getBoolean("isInCar"));//乗降状態の判定 + E.apply();//確定処理 Log.d("nt", "レスポンスを検知しました1"); - - assert parent != null; - if (parent.equals("s")) {//FireBaseの更新情報が"S"のとき=サイト上で第三者ボタンが押されたとき - if (isInCar) { - int importance = NotificationManager.IMPORTANCE_DEFAULT; - NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "通報通知", importance); - channel.setDescription("第3者からの通報を検知しました"); - NotificationManager notificationManager = getSystemService(NotificationManager.class); - notificationManager.createNotificationChannel(channel); - Log.d("nt", "レスポンスを検知しました2"); - notifyMain(); - } - } else { - E.putBoolean("car", !isInCar); - E.apply(); - // SupportFragmentManagerが現在表示しているFragmentを取得 - Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView); + if (documentSnapshot.getBoolean("isReported")==false ) { if (fragment instanceof HomeFragment) { - ((HomeFragment) fragment).onEvent(!isInCar); - } else { - Log.d("nt", "HomeFragment is not visible"); + ((HomeFragment) fragment).onEvent(isInCar); } + }else if(isInCar){ + ResetReported(); + int importance = NotificationManager.IMPORTANCE_DEFAULT; + NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "通報通知", importance); + channel.setDescription("第3者からの通報を検知しました"); + NotificationManager notificationManager = getSystemService(NotificationManager.class); + notificationManager.createNotificationChannel(channel); + Log.d("nt", "レスポンスを検知しました2"); + notifyMain(); + } else{ + ResetReported(); + Log.d("nt", "何もなし" ); } - } - flg = true; - } + } + + } + }); } @@ -231,7 +209,7 @@ public class MainActivity extends AppCompatActivity { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // may need to chain this to a recognizing function BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - HomeFragment homeFragment=new HomeFragment(); +// HomeFragment homeFragment=new HomeFragment(); if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { Log.d("BT", "No permission to connect bluetooth devices"); @@ -289,17 +267,31 @@ public class MainActivity extends AppCompatActivity { } -// @Override -// public void onStop() { -// super.onStop(); -// Intent intent = new Intent(getApplication(), TestService.class); -// startService(intent); -// } + public void ResetReported(){ - //Bluetooth_setupの戻るボタン - public void setupBackButton(boolean enableBackButton) { - ActionBar actionBar = getSupportActionBar(); - actionBar.setDisplayHomeAsUpEnabled(enableBackButton); + SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("app_situation", MODE_PRIVATE); + String IdPref = sharedPreferences.getString("ID", null); + db = FirebaseFirestore.getInstance();//Firebaseとの紐づけ + DocumentReference isReported = db.collection("status").document(IdPref); + Map DEFAULT_ITEM = new HashMap<>();//mapの宣言 + DEFAULT_ITEM.put("isReported", false); + isReported.update("isReported",false).addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void unused) { + Log.d(TAG, "DocumentSnapshot successfully updated!"); + } + }).addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Log.w(TAG, "Error updating document", e); + } + }); + } + @Override + public void onStop() { + super.onStop(); + Intent intent = new Intent(getApplication(), TestService.class); + startService(intent); } } diff --git a/app/src/main/java/com/example/childguard/QR.java b/app/src/main/java/com/example/childguard/QR.java deleted file mode 100644 index 1c9c094..0000000 --- a/app/src/main/java/com/example/childguard/QR.java +++ /dev/null @@ -1,33 +0,0 @@ -//package com.example.childguard; -// -//import android.graphics.Color; -//import android.graphics.drawable.Drawable; -//import android.os.Bundle; -//import android.widget.TextView; -// -//import androidx.appcompat.app.AppCompatActivity; -// -//public class QR extends AppCompatActivity { -// String get_on="乗車状態"; -// String get_off ="降車状態"; -// TextView tv=findViewById(R.id.situation); -// @Override -// protected void onCreate(Bundle savedInstanceState){ -// super.onCreate(savedInstanceState); -// setContentView(R.layout.fragment_qr); -// //多分いらないコード -// findViewById(R.id.camera).setOnClickListener( -// v -> { -// if(get_on.equals(tv.getText().toString())){ -// tv.setText(get_off); -// findViewById(R.id.situation_bg).setBackgroundColor(Color.parseColor("#dcdcdc")); -// } -// else { -// tv.setText(get_on); -// findViewById(R.id.situation_bg).setBackgroundColor(Color.parseColor("#ff4500")); -// } -// } -// ); -// } -// -//} diff --git a/app/src/main/java/com/example/childguard/QRFragment.java b/app/src/main/java/com/example/childguard/QRFragment.java deleted file mode 100644 index 5870462..0000000 --- a/app/src/main/java/com/example/childguard/QRFragment.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.example.childguard; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Bundle; - -import androidx.activity.result.ActivityResultLauncher; -import androidx.activity.result.contract.ActivityResultContracts; -import androidx.browser.customtabs.CustomTabsIntent; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentTransaction; - -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.Toast; - -import com.google.zxing.integration.android.IntentIntegrator; -import com.google.zxing.integration.android.IntentResult; -import com.journeyapps.barcodescanner.ScanContract; -import com.journeyapps.barcodescanner.ScanOptions; - -import java.util.Objects; - -/** - * A simple {@link Fragment} subclass. - * Use the {@link QRFragment#newInstance} factory method to - * create an instance of this fragment. - */ -public class QRFragment extends Fragment { - //QRコードから受け取ったURLの受け渡しの宣言 -// OnDataPass dataPass; - // TODO: Rename parameter arguments, choose names that match - // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER - private static final String ARG_PARAM1 = "param1"; - private static final String ARG_PARAM2 = "param2"; - - // TODO: Rename and change types of parameters - private String mParam1; - private String mParam2; - - public QRFragment() { - // Required empty public constructor - } - - /** - * Use this factory method to create a new instance of - * this fragment using the provided parameters. - * - * @param param1 Parameter 1. - * @param param2 Parameter 2. - * @return A new instance of fragment QRFragment. - */ - // TODO: Rename and change types and number of parameters - public static QRFragment newInstance(String param1, String param2) { - QRFragment fragment = new QRFragment(); - Bundle args = new Bundle(); - args.putString(ARG_PARAM1, param1); - args.putString(ARG_PARAM2, param2); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - mParam1 = getArguments().getString(ARG_PARAM1); - mParam2 = getArguments().getString(ARG_PARAM2); - } - - - } - - private final ActivityResultLauncher fragmentLauncher = registerForActivityResult(new ScanContract(), - result -> { - String contents = result.getContents(); - if (contents == null) { - Toast.makeText(getContext(), "QRコードが読み取れませんでした", Toast.LENGTH_LONG).show(); - } else if (!contents.contains("https://practicefirestore1-8808c.web.app/")) { - Toast.makeText(getContext(), "Chiled Guardに対応するQRコードではありません", Toast.LENGTH_LONG).show(); - } else { - //URLの表示 - Toast.makeText(getContext(), contents, Toast.LENGTH_SHORT).show(); - //ブラウザを起動し、URL先のサイトを開く - CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); - CustomTabsIntent customTabsIntent = builder.build(); - customTabsIntent.launchUrl(requireContext(), Uri.parse(contents)); - } - - getParentFragmentManager().popBackStack(); - }); - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - // Inflate the layout for this fragment - View view = inflater.inflate(R.layout.fragment_qr, container, false); - - - Log.d("QRFragment", "onClick: called"); - //QRリーダ起動 - fragmentLauncher.launch(new ScanOptions()); - - return view; - } - //画面遷移メソッド - private void replaceFragment(Fragment fragment) { - // フラグメントマネージャーの取得 - FragmentManager manager = getParentFragmentManager(); // アクティビティではgetSupportFragmentManager()? - // フラグメントトランザクションの開始 - FragmentTransaction transaction = manager.beginTransaction(); - // レイアウトをfragmentに置き換え(追加) - transaction.replace(R.id.fragmentContainerView, fragment); - // 置き換えのトランザクションをバックスタックに保存する - transaction.addToBackStack(null); - // フラグメントトランザクションをコミット - transaction.commit(); - } -} - diff --git a/app/src/main/java/com/example/childguard/QrPrintFragment.java b/app/src/main/java/com/example/childguard/QrPrintFragment.java deleted file mode 100644 index 88ac807..0000000 --- a/app/src/main/java/com/example/childguard/QrPrintFragment.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.example.childguard; - -import static android.content.Context.MODE_PRIVATE; - -import android.content.SharedPreferences; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.drawable.BitmapDrawable; -import android.os.Bundle; - -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentTransaction; -import androidx.print.PrintHelper; - -import android.preference.PreferenceManager; -import android.util.AndroidRuntimeException; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.WriterException; -import com.journeyapps.barcodescanner.BarcodeEncoder; - -/** - * A simple {@link Fragment} subclass. - * Use the {@link QrPrintFragment#newInstance} factory method to - * create an instance of this fragment. - */ -public class QrPrintFragment extends Fragment { - - // TODO: Rename parameter arguments, choose names that match - // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER - private static final String ARG_PARAM1 = "param1"; - private static final String ARG_PARAM2 = "param2"; - - // TODO: Rename and change types of parameters - private String mParam1; - private String mParam2; - - public QrPrintFragment() { - // Required empty public constructor - } - - /** - * Use this factory method to create a new instance of - * this fragment using the provided parameters. - * - * @param param1 Parameter 1. - * @param param2 Parameter 2. - * @return A new instance of fragment QrPrintFragment. - */ - // TODO: Rename and change types and number of parameters - public static QrPrintFragment newInstance(String param1, String param2) { - QrPrintFragment fragment = new QrPrintFragment(); - Bundle args = new Bundle(); - args.putString(ARG_PARAM1, param1); - args.putString(ARG_PARAM2, param2); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate (Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - mParam1 = getArguments().getString(ARG_PARAM1); - mParam2 = getArguments().getString(ARG_PARAM2); - - } - } - - // @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - //共有プリファレンス全体の準備 - SharedPreferences sharedPreferences = getActivity().getSharedPreferences("app_situation", MODE_PRIVATE); - //User毎のドメインを保存する - String IdPref=sharedPreferences.getString("ID",null); - // Inflate the layout for this fragment - View view=inflater.inflate(R.layout.fragment_qr_print, container, false);; - //固定のドメイン - String KoteiURL = "https://practicefirestore1-8808c.web.app/?id="; - //すべてのドメイン - String AllURL; - //IdPrefにの値が初期値の場合 - if(IdPref==null) { - //User毎のドメイン - String userURL = getArguments().getString("STR_KEY"); - //キー"ID"の値をuserURLの値にする - SharedPreferences.Editor e = sharedPreferences.edit(); - e.putString("ID", userURL); - //確定処理 - e.apply(); - //二つのドメインを合成する - AllURL=KoteiURL+userURL; - }else{ - //二つのドメインを合成する - AllURL=KoteiURL+IdPref; - } - - int size = 2500; - ImageView imageViewQrCode; - Bitmap QRGazou; - try { - //QRコード生成 - BarcodeEncoder barcodeEncoder = new BarcodeEncoder(); - Bitmap bitmapqr = barcodeEncoder.encodeBitmap(AllURL, BarcodeFormat.QR_CODE, size, size); - imageViewQrCode = (ImageView) view.findViewById(R.id.qr_view); - imageViewQrCode.setTranslationX(1000); - imageViewQrCode.setTranslationY(1000); - imageViewQrCode.setImageBitmap(bitmapqr); - } catch (WriterException e) { - throw new AndroidRuntimeException("Barcode Error.", e); - } - // 画像合成の準備 - // ここのエラーは直すと何故か動かなくなる。このままで動くので放置 - Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a_group_qr_sos); - Bitmap bitmap1 = ((BitmapDrawable) imageViewQrCode.getDrawable()).getBitmap(); - int width = bitmap.getWidth(); // 元ファイルの幅取得 - int height = bitmap.getHeight(); // 元ファイルの高さ取得 - QRGazou = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - //Canvasの準備 - Canvas canvas = new Canvas(QRGazou); - //画像のサイズの調整 - int disWidth = (width - bitmap1.getWidth()) / 2; - int disHeight = (int) ((height - bitmap1.getHeight()) / 1.3); - canvas.drawBitmap(bitmap, 0, 0, (Paint) null); // image, x座標, y座標, Paintインスタンス - canvas.drawBitmap(bitmap1, disWidth, disHeight, (Paint) null); // 画像合成 - //Androidからプリンターへ印刷指示を出すサポートライブラリ - PrintHelper printHelper = new PrintHelper(getActivity()); - printHelper.setColorMode(PrintHelper.COLOR_MODE_COLOR); - printHelper.setScaleMode(PrintHelper.SCALE_MODE_FIT); - printHelper.printBitmap("job_name", QRGazou); - HomeFragment homeFragment=new HomeFragment(); -// replaceFragment(homeFragment); - return view; - } - //画面遷移メソッド - private void replaceFragment(Fragment fragment) { - // フラグメントマネージャーの取得 - FragmentManager manager = getParentFragmentManager(); // アクティビティではgetSupportFragmentManager()? - // フラグメントトランザクションの開始 - FragmentTransaction transaction = manager.beginTransaction(); - // レイアウトをfragmentに置き換え(追加) - transaction.replace(R.id.fragmentContainerView, fragment); - // 置き換えのトランザクションをバックスタックに保存する - transaction.addToBackStack(null); - // フラグメントトランザクションをコミット - transaction.commit(); - } -} \ No newline at end of file diff --git a/app/src/main/java/com/example/childguard/SettingFragment.java b/app/src/main/java/com/example/childguard/SettingFragment.java index 6fd9aa9..712e05e 100644 --- a/app/src/main/java/com/example/childguard/SettingFragment.java +++ b/app/src/main/java/com/example/childguard/SettingFragment.java @@ -76,18 +76,16 @@ public class SettingFragment extends Fragment { Toast.makeText(getActivity(), "再印刷", Toast.LENGTH_SHORT).show(); getParentFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragmentContainerView, GenerateQrFragment.newInstance(sharedPreferences.getString("ID", "none"))).commit(); } else { - String valueParent = "placeholder"; - String valueBorn = "placeholder"; - Map user = new HashMap<>();//mapの宣言 + Map DEFAULT_ITEM = new HashMap<>();//mapの宣言 Log.d("HomeFragment", "onClick is called"); //mapに入れる - user.put("parent", valueParent); - user.put("born", valueBorn); + DEFAULT_ITEM.put("isInCar", false); + DEFAULT_ITEM.put("isReported", false); //新しいドキュメントにIDを作って追加 - db.collection("users") - .add(user) + db.collection("status") + .add(DEFAULT_ITEM) .addOnSuccessListener(documentReference -> { //成功したら //documentReference.getId()でID取得 @@ -95,6 +93,7 @@ public class SettingFragment extends Fragment { SharedPreferences.Editor e = sharedPreferences.edit(); // キー"alreadySaved"の値をtrueにする e.putBoolean("alreadySaved", true); + //確定処理 e.apply(); //画面遷移&ID受け渡し diff --git a/app/src/main/java/com/example/childguard/TestService.java b/app/src/main/java/com/example/childguard/TestService.java index 00c9c31..004db02 100644 --- a/app/src/main/java/com/example/childguard/TestService.java +++ b/app/src/main/java/com/example/childguard/TestService.java @@ -5,50 +5,101 @@ import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.IBinder; import android.os.Vibrator; import android.util.Log; +import android.widget.Toast; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; +import androidx.fragment.app.Fragment; + +import com.google.android.gms.tasks.OnFailureListener; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.firebase.firestore.DocumentReference; +import com.google.firebase.firestore.DocumentSnapshot; +import com.google.firebase.firestore.EventListener; +import com.google.firebase.firestore.FirebaseFirestore; +import com.google.firebase.firestore.FirebaseFirestoreException; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executor; public class TestService extends Service { + FirebaseFirestore db; + DocumentReference mDocRef; + public static final String TAG = "InspirationQuote"; + + + @Override public int onStartCommand(Intent intent, int flags, int startId) { - - - audioStart(); - - return START_NOT_STICKY; - + SharedPreferences sharedPreferences = getSharedPreferences("app_situation", MODE_PRIVATE); + String IdPref = sharedPreferences.getString("ID", null); + if (IdPref == null) { + Log.d("onResume", "ID not initialized."); + } else { + mDocRef = FirebaseFirestore.getInstance().document("status/" + IdPref);//現在の位置を取得 + initNotification(mDocRef); + } + return flags; } - private void audioStart(){ + private void initNotification(DocumentReference mDocRef) { + + // Init pref + SharedPreferences sharedPreferences = getSharedPreferences("app_situation",MODE_PRIVATE); + + mDocRef.addSnapshotListener( new EventListener() { + @Override + public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { + + Log.d("nt", "イベント開始"); + //共有プリファレンス 書き込みの準備 + SharedPreferences.Editor E = sharedPreferences.edit(); + //車の乗り降りを管理するtrue=乗車、false=降車 + if (documentSnapshot.exists()) { + Boolean isInCar = sharedPreferences.getBoolean("isInCarPref", false);//現在の乗降状態を保存する共有プリファレンス + E.putBoolean("isInCarPref", documentSnapshot.getBoolean("isInCar"));//乗降状態の判定 + E.apply();//確定処理 + Log.d("nt", "レスポンスを検知しました1"); + if (documentSnapshot.getBoolean("isReported")==true && isInCar==true) { + ResetReported(); + int importance = NotificationManager.IMPORTANCE_DEFAULT; + NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "通報通知", importance); + channel.setDescription("第3者からの通報を検知しました"); + NotificationManager notificationManager = getSystemService(NotificationManager.class); + notificationManager.createNotificationChannel(channel); + Log.d("nt", "レスポンスを検知しました2"); + notifyMain(); + } else{ + ResetReported(); + Log.d("nt", "何もなし" ); + } + } + + } + + }); + } + public void notifyMain() { //↓通知をする際に起動するバイブレーション ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(1000); - //通知のやつ↓ - int importance = NotificationManager.IMPORTANCE_DEFAULT; - - NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "通報通知", importance); - //説明・説明 ここに通知の説明を書くことができる↓ - channel.setDescription("第3者からの通報を検知しました"); - - NotificationManager notificationManager = getSystemService(NotificationManager.class); - notificationManager.createNotificationChannel(channel); - //通知のやつ↑ - Log.d("nt","レスポンスを検知しました2"); //↓通知の詳細設定的な奴 NotificationCompat.Builder builder = new NotificationCompat - .Builder(this, "CHANNEL_ID") .setSmallIcon(android.R.drawable.ic_menu_info_details) .setContentTitle("通報検知") .setContentText("子供の置き去りを検知しました。") .setPriority(NotificationCompat.PRIORITY_DEFAULT); + NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling @@ -61,14 +112,31 @@ public class TestService extends Service { return; } notificationManager.notify(R.string.app_name, builder.build()); - } + public void ResetReported(){ + + SharedPreferences sharedPreferences =getSharedPreferences("app_situation", MODE_PRIVATE); + String IdPref = sharedPreferences.getString("ID", null); + db = FirebaseFirestore.getInstance();//Firebaseとの紐づけ + DocumentReference isReported = db.collection("status").document(IdPref); + Map DEFAULT_ITEM = new HashMap<>();//mapの宣言 + DEFAULT_ITEM.put("isReported", false); + isReported.update("isReported",false).addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void unused) { + Log.d(TAG, "DocumentSnapshot successfully updated!"); + } + }).addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Log.w(TAG, "Error updating document", e); + } + }); + } @Nullable @Override public IBinder onBind(Intent intent) { - - return null; } } \ No newline at end of file