Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package info.rekayasa.polisipro;
- import android.Manifest;
- import android.app.ProgressDialog;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentSender;
- import android.content.pm.ActivityInfo;
- import android.content.pm.PackageManager;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Color;
- import android.location.Location;
- import android.location.LocationManager;
- import android.net.Uri;
- import android.os.Bundle;
- import android.os.Environment;
- import android.provider.MediaStore;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.design.widget.FloatingActionButton;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.content.ContextCompat;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.Toolbar;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.common.api.PendingResult;
- import com.google.android.gms.common.api.ResultCallback;
- import com.google.android.gms.common.api.Status;
- import com.google.android.gms.location.LocationListener;
- import com.google.android.gms.location.LocationRequest;
- import com.google.android.gms.location.LocationServices;
- import com.google.android.gms.location.LocationSettingsRequest;
- import com.google.android.gms.location.LocationSettingsResult;
- import com.google.android.gms.location.LocationSettingsStatusCodes;
- import com.google.firebase.auth.FirebaseAuth;
- import com.google.firebase.database.DataSnapshot;
- import com.google.firebase.database.DatabaseError;
- import com.google.firebase.database.DatabaseReference;
- import com.google.firebase.database.FirebaseDatabase;
- import com.google.firebase.database.Query;
- import com.google.firebase.database.ServerValue;
- import com.google.firebase.database.ValueEventListener;
- import com.google.firebase.storage.FirebaseStorage;
- import com.google.firebase.storage.OnProgressListener;
- import com.google.firebase.storage.StorageReference;
- import com.google.firebase.storage.UploadTask;
- import org.json.JSONArray;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Iterator;
- import java.util.Locale;
- import static com.google.android.gms.internal.zzax.getKey;
- public class ReportActivity extends AppCompatActivity implements
- GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
- LocationListener, ResultCallback<LocationSettingsResult> {
- TextView tvAccuracy, tvLocation, tvAccuracyStatus;
- Toolbar toolbar;
- FloatingActionButton fab;
- Button btnSend;
- ImageView ivPhoto;
- EditText etReport;
- Uri fileUri;
- JSONArray recipients;
- double latitude, longitude;
- private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
- public static final int MEDIA_TYPE_IMAGE = 1;
- private static final String IMAGE_DIRECTORY_NAME = "KlikPolisi";
- String fileName, userId, reportContent, category;
- private static String fullName;
- long timestamp;
- private StorageReference mStorage;
- private DatabaseReference mDatabase, mUserRef, mReportRef, mUserToken;
- private FirebaseAuth mAuth;
- ProgressDialog mProgressDialog;
- Location mLastLocation;
- private GoogleApiClient mGoogleApiClient;
- private LocationRequest mLocationRequest;
- public static int LOCATION_REQUEST = 300;
- int REQUEST_CHECK_SETTINGS = 200;
- LocationManager mLocationManager;
- public String lat, lng, accuracy;
- float acc;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_report);
- this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- Bundle extras = getIntent().getExtras();
- category = extras.getString("category");
- setTitle(category);
- System.out.println("Category: " + category);
- mProgressDialog = new ProgressDialog(this);
- // mStorage = FirebaseStorage.getInstance().getReference();
- mDatabase = FirebaseDatabase.getInstance().getReference();
- mAuth = FirebaseAuth.getInstance();
- fab = (FloatingActionButton) findViewById(R.id.fab);
- ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
- etReport = (EditText) findViewById(R.id.etReport);
- tvLocation = (TextView) findViewById(R.id.tvLocation);
- tvAccuracy = (TextView) findViewById(R.id.tvAccuracy);
- tvAccuracyStatus = (TextView) findViewById(R.id.tvAccuracyStatus);
- fullName = getFullName();
- // getUserToken();
- btnSend = (Button) findViewById(R.id.btnSend);
- btnSend.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mProgressDialog.setMessage("Mengirim laporan...");
- mProgressDialog.show();
- saveReport();
- }
- });
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
- fab.setEnabled(false);
- ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
- } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- fab.setEnabled(false);
- ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
- } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- fab.setEnabled(false);
- ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
- }
- if (category.equals("Kemacetan")) {
- fab.setBackgroundTintList(getResources().getColorStateList(R.color.orange));
- } else if (category.equals("Kecelakaan")) {
- fab.setBackgroundTintList(getResources().getColorStateList(R.color.red));
- } else if (category.equals("Tindak Kriminal")) {
- fab.setBackgroundTintList(getResources().getColorStateList(R.color.green));
- } else if (category.equals("Bencana")) {
- fab.setBackgroundTintList(getResources().getColorStateList(R.color.blue));
- }
- fab.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- takePicture();
- }
- });
- buildGoogleApiClient();
- }
- private void saveReport() {
- reportContent = etReport.getText().toString();
- if (TextUtils.isEmpty(reportContent)) {
- etReport.setError("Harus diisi!");
- }
- mReportRef = mDatabase.child("reports");
- final String reportKey = mReportRef.push().getKey();
- if (reportKey.equals("")){
- return;
- }
- System.out.println("fileName: " + fileName);
- System.out.println("fileUri.getLastPathSegment: " + fileUri.getLastPathSegment());
- StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("Photos/" +
- fileUri.getLastPathSegment());
- storageRef.child("Photos");
- Uri file = Uri.fromFile(new File(fileUri.getPath()));
- UploadTask uploadTask = storageRef.putFile(file);
- uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
- @Override
- public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
- System.out.println("Progress: " + (taskSnapshot.getBytesTransferred()));
- System.out.println("Total: " + taskSnapshot.getTotalByteCount());
- if (taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount()){
- System.out.println("Upload complete!");
- mReportRef.child(reportKey).child("timestamp").setValue(ServerValue.TIMESTAMP);
- Query query = mReportRef.child(reportKey).child("timestamp");
- query.addListenerForSingleValueEvent(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- timestamp = dataSnapshot.getValue(long.class);
- System.out.println("fullName2: " + fullName);
- System.out.println("timestamp: " + timestamp);
- try {
- latitude = Double.parseDouble(lat);
- longitude = Double.parseDouble(lng);
- } catch (Exception e){
- System.out.println("Exeption: " + e.toString());
- }
- Report report = new Report(userId, fullName, latitude, longitude,
- timestamp, reportContent, category, fileUri.getLastPathSegment());
- mReportRef.child(reportKey).setValue(report);
- mDatabase.child("new-reports").child(reportKey).setValue(report);
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- System.out.println("Database Error: " + databaseError);
- }
- });
- mProgressDialog.dismiss();
- getUserToken();
- finish();
- }
- }
- });
- //
- }
- private void takePicture() {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
- System.out.println("fileUri: " + fileUri.getPath());
- intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
- // start the image capture Intent
- startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
- }
- /**
- * Creating file uri to store image/video
- */
- public Uri getOutputMediaFileUri(int type) {
- return Uri.fromFile(getOutputMediaFile(type));
- }
- /*
- * returning image
- */
- private static File getOutputMediaFile(int type) {
- // External sdcard location
- File mediaStorageDir = new File(
- Environment
- .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
- IMAGE_DIRECTORY_NAME);
- // Create the storage directory if it does not exist
- if (!mediaStorageDir.exists()) {
- if (!mediaStorageDir.mkdirs()) {
- Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
- + IMAGE_DIRECTORY_NAME + " directory");
- return null;
- }
- }
- // Create a media file name
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
- Locale.getDefault()).format(new Date());
- File mediaFile;
- if (type == MEDIA_TYPE_IMAGE) {
- mediaFile = new File(mediaStorageDir.getPath() + File.separator
- + "IMG_" + timeStamp + ".jpg");
- } else {
- return null;
- }
- return mediaFile;
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
- if (requestCode == 0) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
- && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
- fab.setEnabled(true);
- }
- } else if (requestCode == LOCATION_REQUEST) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
- && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
- Toast.makeText(getApplicationContext(), "Akses lokasi diizinkan",
- Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(getApplicationContext(), "Aplikasi harus diizinkan mengakses lokasi!",
- Toast.LENGTH_LONG).show();
- }
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
- try {
- System.out.println("fileUri.getPath" + fileUri.getPath());
- String getPath = fileUri.getPath();
- if (getPath.isEmpty()) {
- getPath = fileUri.getPath();
- System.out.println("getPath is empty...");
- }
- resizePhoto(getPath);
- previewCapturedImage();
- } catch (Exception e) {
- Toast.makeText(getApplicationContext(), "Gagal memuat foto. Silahkan ulangi lagi!", Toast.LENGTH_LONG).show();
- System.out.println("Gagal mengecilkan foto!");
- e.printStackTrace();
- }
- } else if (requestCode == REQUEST_CHECK_SETTINGS) {
- if (resultCode == RESULT_OK) {
- Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
- } else {
- Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
- }
- }
- }
- /*
- * Display image from a path to ImageView
- */
- private void previewCapturedImage() {
- // Get the dimensions of the View
- int targetW = ivPhoto.getWidth();
- int targetH = ivPhoto.getHeight();
- // Get the dimensions of the bitmap
- BitmapFactory.Options bmOptions = new BitmapFactory.Options();
- bmOptions.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
- int photoW = bmOptions.outWidth;
- int photoH = bmOptions.outHeight;
- System.out.println("photoW: " + photoW + ", " + "photoH: " + photoH);
- // Determine how much to scale down the image
- int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
- // Decode the image file into a Bitmap sized to fill the View
- bmOptions.inJustDecodeBounds = false;
- bmOptions.inSampleSize = scaleFactor;
- bmOptions.inPurgeable = true;
- Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
- ivPhoto.setImageBitmap(bitmap);
- }
- private void resizePhoto(String uri) {
- Bitmap photo = BitmapFactory.decodeFile(uri);
- float scale = photo.getHeight() / 720f;
- int width = (int) (Math.round(photo.getWidth() / scale));
- photo = Bitmap.createScaledBitmap(photo, width, 720, false);
- ByteArrayOutputStream bytes = new ByteArrayOutputStream();
- photo.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
- File mediaStorageDir = new File(
- Environment
- .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
- IMAGE_DIRECTORY_NAME);
- File resizedFile;
- resizedFile = new File(mediaStorageDir.getPath() + File.separator
- + fileUri.getLastPathSegment());
- try {
- resizedFile.createNewFile();
- FileOutputStream fo = new FileOutputStream(resizedFile);
- fo.write(bytes.toByteArray());
- fo.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onConnected(@Nullable Bundle bundle) {
- mLocationRequest = LocationRequest.create();
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- mLocationRequest.setInterval(5000);
- mLocationRequest.setFastestInterval(1000);
- if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
- != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
- android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(this,
- new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
- android.Manifest.permission.ACCESS_COARSE_LOCATION},
- LOCATION_REQUEST);
- return;
- }
- LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
- mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
- if (mLastLocation != null) {
- lat = String.valueOf(mLastLocation.getLatitude());
- lng = String.valueOf(mLastLocation.getLongitude());
- accuracy = String.valueOf(mLastLocation.getAccuracy());
- acc = mLastLocation.getAccuracy();
- }
- mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
- .addLocationRequest(mLocationRequest);
- builder.setAlwaysShow(true);
- PendingResult<LocationSettingsResult> result =
- LocationServices.SettingsApi.checkLocationSettings(
- mGoogleApiClient,
- builder.build()
- );
- result.setResultCallback(this);
- updateUI();
- }
- private void updateUI() {
- tvLocation.setText("Lokasi: " + lat + ", " + lng);
- tvAccuracy.setText("Akurasi: " + accuracy + " m");
- if (acc < 15) {
- tvAccuracyStatus.setText("Lokasi akurat");
- tvAccuracyStatus.setTextColor(Color.parseColor("#0000FF"));
- } else {
- tvAccuracyStatus.setText("Lokasi belum akurat");
- tvAccuracyStatus.setTextColor(Color.parseColor("#FF4081"));
- }
- }
- @Override
- public void onConnectionSuspended(int i) {
- }
- @Override
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
- buildGoogleApiClient();
- }
- @Override
- public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
- final Status status = locationSettingsResult.getStatus();
- switch (status.getStatusCode()) {
- case LocationSettingsStatusCodes.SUCCESS:
- // NO need to show the dialog;
- break;
- case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
- // Location settings are not satisfied. Show the user a dialog
- try {
- // Show the dialog by calling startResolutionForResult(), and check the result
- // in onActivityResult().
- status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
- } catch (IntentSender.SendIntentException e) {
- //failed to show
- }
- break;
- case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
- // Location settings are unavailable so not possible to show any dialog now
- break;
- }
- }
- @Override
- public void onLocationChanged(Location location) {
- lat = String.valueOf(location.getLatitude());
- lng = String.valueOf(location.getLongitude());
- accuracy = String.valueOf(location.getAccuracy());
- acc = location.getAccuracy();
- updateUI();
- Log.d("ReportActivity", "Location is updated...");
- }
- synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API)
- .build();
- }
- @Override
- protected void onStart() {
- super.onStart();
- mGoogleApiClient.connect();
- }
- @Override
- protected void onStop() {
- super.onStop();
- mGoogleApiClient.disconnect();
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- mGoogleApiClient.disconnect();
- }
- private String getFullName() {
- userId = mAuth.getCurrentUser().getUid();
- mUserRef = mDatabase.child("users").child(userId).child("fullName");
- mUserRef.addListenerForSingleValueEvent(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- fullName = dataSnapshot.getValue(String.class);
- System.out.println("fullName: " + fullName);
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- }
- });
- return fullName;
- }
- private void getUserToken(){
- recipients = new JSONArray();
- System.out.println("recipients: " + recipients.length());
- final String body = category + " telah terjadi.";
- mUserToken = mDatabase.child("user-token");
- mUserToken.addValueEventListener(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- Iterator<DataSnapshot> tokenSnapshot = dataSnapshot.getChildren().iterator();
- do {
- String key = tokenSnapshot.next().getKey();
- String userToken = dataSnapshot.child(key).child("userToken").getValue(String.class);
- // String token = userToken.getUserToken();
- System.out.println("datasnapshot: " + dataSnapshot);
- System.out.println("key: " + key);
- System.out.println("usertoken: " + userToken);
- recipients.put(userToken);
- } while (tokenSnapshot.hasNext());
- System.out.println("jsonarray: " + recipients);
- FcmSendMessage fcmSendMessage = new FcmSendMessage();
- fcmSendMessage.sendMessage(recipients, "", body, "", "Uji coba dari device");
- // finish();
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement