Advertisement
rachmadi

Contoh Camera

Mar 9th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 22.99 KB | None | 0 0
  1. import android.Manifest;
  2. import android.app.ProgressDialog;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.IntentSender;
  6. import android.content.pm.ActivityInfo;
  7. import android.content.pm.PackageManager;
  8. import android.graphics.Bitmap;
  9. import android.graphics.BitmapFactory;
  10. import android.graphics.Color;
  11. import android.location.Location;
  12. import android.location.LocationManager;
  13. import android.net.Uri;
  14. import android.os.Bundle;
  15. import android.os.Environment;
  16. import android.provider.MediaStore;
  17. import android.support.annotation.NonNull;
  18. import android.support.annotation.Nullable;
  19. import android.support.design.widget.FloatingActionButton;
  20. import android.support.v4.app.ActivityCompat;
  21. import android.support.v4.content.ContextCompat;
  22. import android.support.v7.app.AppCompatActivity;
  23. import android.support.v7.widget.Toolbar;
  24. import android.text.TextUtils;
  25. import android.util.Log;
  26. import android.view.View;
  27. import android.widget.Button;
  28. import android.widget.EditText;
  29. import android.widget.ImageView;
  30. import android.widget.TextView;
  31. import android.widget.Toast;
  32.  
  33. import com.google.android.gms.common.ConnectionResult;
  34. import com.google.android.gms.common.api.GoogleApiClient;
  35. import com.google.android.gms.common.api.PendingResult;
  36. import com.google.android.gms.common.api.ResultCallback;
  37. import com.google.android.gms.common.api.Status;
  38. import com.google.android.gms.location.LocationListener;
  39. import com.google.android.gms.location.LocationRequest;
  40. import com.google.android.gms.location.LocationServices;
  41. import com.google.android.gms.location.LocationSettingsRequest;
  42. import com.google.android.gms.location.LocationSettingsResult;
  43. import com.google.android.gms.location.LocationSettingsStatusCodes;
  44. import com.google.firebase.auth.FirebaseAuth;
  45. import com.google.firebase.database.DataSnapshot;
  46. import com.google.firebase.database.DatabaseError;
  47. import com.google.firebase.database.DatabaseReference;
  48. import com.google.firebase.database.FirebaseDatabase;
  49. import com.google.firebase.database.Query;
  50. import com.google.firebase.database.ServerValue;
  51. import com.google.firebase.database.ValueEventListener;
  52. import com.google.firebase.storage.FirebaseStorage;
  53. import com.google.firebase.storage.OnProgressListener;
  54. import com.google.firebase.storage.StorageReference;
  55. import com.google.firebase.storage.UploadTask;
  56.  
  57. import org.json.JSONArray;
  58.  
  59. import java.io.ByteArrayOutputStream;
  60. import java.io.File;
  61. import java.io.FileOutputStream;
  62. import java.io.IOException;
  63. import java.text.SimpleDateFormat;
  64. import java.util.Date;
  65. import java.util.Iterator;
  66. import java.util.Locale;
  67.  
  68. import static com.google.android.gms.internal.zzax.getKey;
  69.  
  70.  
  71. public class ReportActivity extends AppCompatActivity implements
  72.         GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
  73.         LocationListener, ResultCallback<LocationSettingsResult> {
  74.  
  75.     TextView tvAccuracy, tvLocation, tvAccuracyStatus;
  76.     Toolbar toolbar;
  77.     FloatingActionButton fab;
  78.     Button btnSend;
  79.     ImageView ivPhoto;
  80.     EditText etReport;
  81.  
  82.     Uri fileUri;
  83.  
  84.     JSONArray recipients;
  85.  
  86.     double latitude, longitude;
  87.  
  88.     private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
  89.     public static final int MEDIA_TYPE_IMAGE = 1;
  90.     private static final String IMAGE_DIRECTORY_NAME = "KlikPolisi";
  91.  
  92.     String fileName, userId, reportContent, category;
  93.     private static String fullName;
  94.     long timestamp;
  95.  
  96.     private StorageReference mStorage;
  97.     private DatabaseReference mDatabase, mUserRef, mReportRef, mUserToken;
  98.     private FirebaseAuth mAuth;
  99.  
  100.     ProgressDialog mProgressDialog;
  101.  
  102.     Location mLastLocation;
  103.     private GoogleApiClient mGoogleApiClient;
  104.     private LocationRequest mLocationRequest;
  105.     public static int LOCATION_REQUEST = 300;
  106.     int REQUEST_CHECK_SETTINGS = 200;
  107.     LocationManager mLocationManager;
  108.  
  109.     public String lat, lng, accuracy;
  110.     float acc;
  111.  
  112.     @Override
  113.     protected void onCreate(Bundle savedInstanceState) {
  114.         super.onCreate(savedInstanceState);
  115.  
  116.         setContentView(R.layout.activity_report);
  117.         this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  118.  
  119.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  120.         setSupportActionBar(toolbar);
  121.         Bundle extras = getIntent().getExtras();
  122.         category = extras.getString("category");
  123.         setTitle(category);
  124.         System.out.println("Category: " + category);
  125.  
  126.         mProgressDialog = new ProgressDialog(this);
  127.  
  128. //        mStorage = FirebaseStorage.getInstance().getReference();
  129.         mDatabase = FirebaseDatabase.getInstance().getReference();
  130.         mAuth = FirebaseAuth.getInstance();
  131.  
  132.         fab = (FloatingActionButton) findViewById(R.id.fab);
  133.         ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
  134.         etReport = (EditText) findViewById(R.id.etReport);
  135.         tvLocation = (TextView) findViewById(R.id.tvLocation);
  136.         tvAccuracy = (TextView) findViewById(R.id.tvAccuracy);
  137.         tvAccuracyStatus = (TextView) findViewById(R.id.tvAccuracyStatus);
  138.  
  139.         fullName = getFullName();
  140. //        getUserToken();
  141.  
  142.         btnSend = (Button) findViewById(R.id.btnSend);
  143.         btnSend.setOnClickListener(new View.OnClickListener() {
  144.             @Override
  145.             public void onClick(View view) {
  146.                 mProgressDialog.setMessage("Mengirim laporan...");
  147.                 mProgressDialog.show();
  148.                 saveReport();
  149.             }
  150.         });
  151.  
  152.         if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
  153.             fab.setEnabled(false);
  154.             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
  155.         } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  156.             fab.setEnabled(false);
  157.             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
  158.         } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  159.             fab.setEnabled(false);
  160.             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
  161.         }
  162.  
  163.  
  164.         if (category.equals("Kemacetan")) {
  165.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.orange));
  166.         } else if (category.equals("Kecelakaan")) {
  167.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.red));
  168.         } else if (category.equals("Tindak Kriminal")) {
  169.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.green));
  170.         } else if (category.equals("Bencana")) {
  171.             fab.setBackgroundTintList(getResources().getColorStateList(R.color.blue));
  172.         }
  173.  
  174.         fab.setOnClickListener(new View.OnClickListener() {
  175.             @Override
  176.             public void onClick(View view) {
  177.                 takePicture();
  178.             }
  179.         });
  180.  
  181.         buildGoogleApiClient();
  182.     }
  183.  
  184.     private void saveReport() {
  185.         reportContent = etReport.getText().toString();
  186.         if (TextUtils.isEmpty(reportContent)) {
  187.             etReport.setError("Harus diisi!");
  188.         }
  189.  
  190.         mReportRef = mDatabase.child("reports");
  191.         final String reportKey = mReportRef.push().getKey();
  192.         if (reportKey.equals("")){
  193.             return;
  194.         }
  195.         System.out.println("fileName: " + fileName);
  196.         System.out.println("fileUri.getLastPathSegment: " + fileUri.getLastPathSegment());
  197.         StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("Photos/" +
  198.                 fileUri.getLastPathSegment());
  199.         storageRef.child("Photos");
  200.         Uri file = Uri.fromFile(new File(fileUri.getPath()));
  201.         UploadTask uploadTask = storageRef.putFile(file);
  202.         uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
  203.             @Override
  204.             public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
  205.                 System.out.println("Progress: " + (taskSnapshot.getBytesTransferred()));
  206.                 System.out.println("Total: " + taskSnapshot.getTotalByteCount());
  207.                 if (taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount()){
  208.                     System.out.println("Upload complete!");
  209.  
  210.                     mReportRef.child(reportKey).child("timestamp").setValue(ServerValue.TIMESTAMP);
  211.                     Query query = mReportRef.child(reportKey).child("timestamp");
  212.                     query.addListenerForSingleValueEvent(new ValueEventListener() {
  213.                         @Override
  214.                         public void onDataChange(DataSnapshot dataSnapshot) {
  215.                             timestamp = dataSnapshot.getValue(long.class);
  216.                             System.out.println("fullName2: " + fullName);
  217.                             System.out.println("timestamp: " + timestamp);
  218.                             try {
  219.                                 latitude = Double.parseDouble(lat);
  220.                                 longitude = Double.parseDouble(lng);
  221.                             } catch (Exception e){
  222.                                 System.out.println("Exeption: " + e.toString());
  223.                             }
  224.                             Report report = new Report(userId, fullName, latitude, longitude,
  225.                                     timestamp, reportContent, category, fileUri.getLastPathSegment());
  226.                             mReportRef.child(reportKey).setValue(report);
  227.                             mDatabase.child("new-reports").child(reportKey).setValue(report);
  228.                         }
  229.  
  230.                         @Override
  231.                         public void onCancelled(DatabaseError databaseError) {
  232.                             System.out.println("Database Error: " + databaseError);
  233.                         }
  234.                     });
  235.  
  236.                     mProgressDialog.dismiss();
  237.                     getUserToken();
  238.                     finish();
  239.                 }
  240.             }
  241.         });
  242.  
  243. //
  244.     }
  245.  
  246.     private void takePicture() {
  247.         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  248.  
  249.         fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
  250.         System.out.println("fileUri: " + fileUri.getPath());
  251.  
  252.         intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
  253.  
  254.         // start the image capture Intent
  255.         startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
  256.     }
  257.  
  258.     /**
  259.      * Creating file uri to store image/video
  260.      */
  261.     public Uri getOutputMediaFileUri(int type) {
  262.         return Uri.fromFile(getOutputMediaFile(type));
  263.     }
  264.  
  265.     /*
  266.      * returning image
  267.      */
  268.     private static File getOutputMediaFile(int type) {
  269.  
  270.         // External sdcard location
  271.         File mediaStorageDir = new File(
  272.                 Environment
  273.                         .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
  274.                 IMAGE_DIRECTORY_NAME);
  275.  
  276.         // Create the storage directory if it does not exist
  277.         if (!mediaStorageDir.exists()) {
  278.             if (!mediaStorageDir.mkdirs()) {
  279.                 Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
  280.                         + IMAGE_DIRECTORY_NAME + " directory");
  281.                 return null;
  282.             }
  283.         }
  284.  
  285.         // Create a media file name
  286.         String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
  287.                 Locale.getDefault()).format(new Date());
  288.         File mediaFile;
  289.         if (type == MEDIA_TYPE_IMAGE) {
  290.             mediaFile = new File(mediaStorageDir.getPath() + File.separator
  291.                     + "IMG_" + timeStamp + ".jpg");
  292.         } else {
  293.             return null;
  294.         }
  295.  
  296.         return mediaFile;
  297.     }
  298.  
  299.     @Override
  300.     public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  301.         if (requestCode == 0) {
  302.             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
  303.                     && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
  304.                 fab.setEnabled(true);
  305.             }
  306.         } else if (requestCode == LOCATION_REQUEST) {
  307.             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
  308.                     && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
  309.                 Toast.makeText(getApplicationContext(), "Akses lokasi diizinkan",
  310.                         Toast.LENGTH_SHORT).show();
  311.             } else {
  312.                 Toast.makeText(getApplicationContext(), "Aplikasi harus diizinkan mengakses lokasi!",
  313.                         Toast.LENGTH_LONG).show();
  314.             }
  315.         }
  316.     }
  317.  
  318.     @Override
  319.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  320.         super.onActivityResult(requestCode, resultCode, data);
  321.         if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
  322.             try {
  323.                 System.out.println("fileUri.getPath" + fileUri.getPath());
  324.                 String getPath = fileUri.getPath();
  325.                 if (getPath.isEmpty()) {
  326.                     getPath = fileUri.getPath();
  327.                     System.out.println("getPath is empty...");
  328.                 }
  329.                 resizePhoto(getPath);
  330.                 previewCapturedImage();
  331.             } catch (Exception e) {
  332.                 Toast.makeText(getApplicationContext(), "Gagal memuat foto. Silahkan ulangi lagi!", Toast.LENGTH_LONG).show();
  333.                 System.out.println("Gagal mengecilkan foto!");
  334.                 e.printStackTrace();
  335.             }
  336.         } else if (requestCode == REQUEST_CHECK_SETTINGS) {
  337.             if (resultCode == RESULT_OK) {
  338.  
  339.                 Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
  340.             } else {
  341.  
  342.                 Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
  343.             }
  344.         }
  345.  
  346.     }
  347.  
  348.     /*
  349.     * Display image from a path to ImageView
  350.     */
  351.     private void previewCapturedImage() {
  352.  
  353.         // Get the dimensions of the View
  354.         int targetW = ivPhoto.getWidth();
  355.         int targetH = ivPhoto.getHeight();
  356.  
  357.         // Get the dimensions of the bitmap
  358.         BitmapFactory.Options bmOptions = new BitmapFactory.Options();
  359.         bmOptions.inJustDecodeBounds = true;
  360.         BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
  361.         int photoW = bmOptions.outWidth;
  362.         int photoH = bmOptions.outHeight;
  363.  
  364.         System.out.println("photoW: " + photoW + ", " + "photoH: " + photoH);
  365.  
  366.         // Determine how much to scale down the image
  367.         int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
  368.  
  369.         // Decode the image file into a Bitmap sized to fill the View
  370.         bmOptions.inJustDecodeBounds = false;
  371.         bmOptions.inSampleSize = scaleFactor;
  372.         bmOptions.inPurgeable = true;
  373.  
  374.         Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
  375.         ivPhoto.setImageBitmap(bitmap);
  376.     }
  377.  
  378.     private void resizePhoto(String uri) {
  379.         Bitmap photo = BitmapFactory.decodeFile(uri);
  380.         float scale = photo.getHeight() / 720f;
  381.         int width = (int) (Math.round(photo.getWidth() / scale));
  382.  
  383.         photo = Bitmap.createScaledBitmap(photo, width, 720, false);
  384.         ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  385.         photo.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
  386.  
  387.         File mediaStorageDir = new File(
  388.                 Environment
  389.                         .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
  390.                 IMAGE_DIRECTORY_NAME);
  391.  
  392.         File resizedFile;
  393.         resizedFile = new File(mediaStorageDir.getPath() + File.separator
  394.                 + fileUri.getLastPathSegment());
  395.  
  396.         try {
  397.             resizedFile.createNewFile();
  398.             FileOutputStream fo = new FileOutputStream(resizedFile);
  399.             fo.write(bytes.toByteArray());
  400.             fo.close();
  401.         } catch (IOException e) {
  402.             e.printStackTrace();
  403.         }
  404.  
  405.     }
  406.  
  407.     @Override
  408.     public void onConnected(@Nullable Bundle bundle) {
  409.         mLocationRequest = LocationRequest.create();
  410.         mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  411.         mLocationRequest.setInterval(5000);
  412.         mLocationRequest.setFastestInterval(1000);
  413.  
  414.         if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  415.                 != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
  416.                 android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  417.  
  418.             ActivityCompat.requestPermissions(this,
  419.                     new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
  420.                             android.Manifest.permission.ACCESS_COARSE_LOCATION},
  421.                     LOCATION_REQUEST);
  422.             return;
  423.         }
  424.         LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
  425.  
  426.         mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  427.         if (mLastLocation != null) {
  428.             lat = String.valueOf(mLastLocation.getLatitude());
  429.             lng = String.valueOf(mLastLocation.getLongitude());
  430.             accuracy = String.valueOf(mLastLocation.getAccuracy());
  431.             acc = mLastLocation.getAccuracy();
  432.         }
  433.  
  434.         mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  435.  
  436.         LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
  437.                 .addLocationRequest(mLocationRequest);
  438.         builder.setAlwaysShow(true);
  439.         PendingResult<LocationSettingsResult> result =
  440.                 LocationServices.SettingsApi.checkLocationSettings(
  441.                         mGoogleApiClient,
  442.                         builder.build()
  443.                 );
  444.         result.setResultCallback(this);
  445.  
  446.         updateUI();
  447.     }
  448.  
  449.     private void updateUI() {
  450.         tvLocation.setText("Lokasi: " + lat + ", " + lng);
  451.         tvAccuracy.setText("Akurasi: " + accuracy + " m");
  452.         if (acc < 15) {
  453.             tvAccuracyStatus.setText("Lokasi akurat");
  454.             tvAccuracyStatus.setTextColor(Color.parseColor("#0000FF"));
  455.         } else {
  456.             tvAccuracyStatus.setText("Lokasi belum akurat");
  457.             tvAccuracyStatus.setTextColor(Color.parseColor("#FF4081"));
  458.         }
  459.     }
  460.  
  461.     @Override
  462.     public void onConnectionSuspended(int i) {
  463.  
  464.     }
  465.  
  466.     @Override
  467.     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  468.         buildGoogleApiClient();
  469.     }
  470.  
  471.     @Override
  472.     public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
  473.         final Status status = locationSettingsResult.getStatus();
  474.         switch (status.getStatusCode()) {
  475.             case LocationSettingsStatusCodes.SUCCESS:
  476.                 // NO need to show the dialog;
  477.                 break;
  478.  
  479.             case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
  480.                 //  Location settings are not satisfied. Show the user a dialog
  481.                 try {
  482.                     // Show the dialog by calling startResolutionForResult(), and check the result
  483.                     // in onActivityResult().
  484.  
  485.                     status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
  486.  
  487.                 } catch (IntentSender.SendIntentException e) {
  488.                     //failed to show
  489.                 }
  490.                 break;
  491.  
  492.             case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
  493.                 // Location settings are unavailable so not possible to show any dialog now
  494.                 break;
  495.         }
  496.     }
  497.  
  498.     @Override
  499.     public void onLocationChanged(Location location) {
  500.  
  501.         lat = String.valueOf(location.getLatitude());
  502.         lng = String.valueOf(location.getLongitude());
  503.         accuracy = String.valueOf(location.getAccuracy());
  504.         acc = location.getAccuracy();
  505.         updateUI();
  506.         Log.d("ReportActivity", "Location is updated...");
  507.  
  508.     }
  509.  
  510.     synchronized void buildGoogleApiClient() {
  511.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  512.                 .addConnectionCallbacks(this)
  513.                 .addOnConnectionFailedListener(this)
  514.                 .addApi(LocationServices.API)
  515.                 .build();
  516.     }
  517.  
  518.     @Override
  519.     protected void onStart() {
  520.         super.onStart();
  521.         mGoogleApiClient.connect();
  522.     }
  523.  
  524.     @Override
  525.     protected void onStop() {
  526.         super.onStop();
  527.         mGoogleApiClient.disconnect();
  528.     }
  529.  
  530.     @Override
  531.     protected void onDestroy() {
  532.         super.onDestroy();
  533.         mGoogleApiClient.disconnect();
  534.     }
  535.  
  536.     private String getFullName() {
  537.         userId = mAuth.getCurrentUser().getUid();
  538.         mUserRef = mDatabase.child("users").child(userId).child("fullName");
  539.         mUserRef.addListenerForSingleValueEvent(new ValueEventListener() {
  540.             @Override
  541.             public void onDataChange(DataSnapshot dataSnapshot) {
  542.                 fullName = dataSnapshot.getValue(String.class);
  543.                 System.out.println("fullName: " + fullName);
  544.             }
  545.  
  546.             @Override
  547.             public void onCancelled(DatabaseError databaseError) {
  548.  
  549.             }
  550.         });
  551.         return fullName;
  552.     }
  553.  
  554.     private void getUserToken(){
  555.         recipients = new JSONArray();
  556.         System.out.println("recipients: " + recipients.length());
  557.         final String body = category + " telah terjadi.";
  558.         mUserToken = mDatabase.child("user-token");
  559.         mUserToken.addValueEventListener(new ValueEventListener() {
  560.             @Override
  561.             public void onDataChange(DataSnapshot dataSnapshot) {
  562.                 Iterator<DataSnapshot> tokenSnapshot = dataSnapshot.getChildren().iterator();
  563.                 do {
  564.                     String key = tokenSnapshot.next().getKey();
  565.                     String userToken = dataSnapshot.child(key).child("userToken").getValue(String.class);
  566. //                    String token = userToken.getUserToken();
  567.                     System.out.println("datasnapshot: " + dataSnapshot);
  568.                     System.out.println("key: " + key);
  569.                     System.out.println("usertoken: " + userToken);
  570.                     recipients.put(userToken);
  571.                 } while (tokenSnapshot.hasNext());
  572.                 System.out.println("jsonarray: " + recipients);
  573.                 FcmSendMessage fcmSendMessage = new FcmSendMessage();
  574.                 fcmSendMessage.sendMessage(recipients, "", body, "", "Uji coba dari device");
  575. //                finish();
  576.             }
  577.  
  578.             @Override
  579.             public void onCancelled(DatabaseError databaseError) {
  580.  
  581.             }
  582.         });
  583.     }
  584. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement