Advertisement
Combreal

PictGrab.java

Jul 25th, 2022 (edited)
1,654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.10 KB | None | 0 0
  1. --------------------------------MainActivivity.java
  2. package com.example.testactivity;
  3.  
  4. import android.Manifest;
  5. import android.annotation.SuppressLint;
  6. import android.app.Activity;
  7. import android.content.ActivityNotFoundException;
  8. import android.content.ContentValues;
  9. import android.content.Intent;
  10. import android.content.pm.PackageManager;
  11. import android.graphics.Bitmap;
  12. import android.graphics.drawable.BitmapDrawable;
  13. import android.media.MediaScannerConnection;
  14. import android.net.Uri;
  15. import android.os.Build;
  16. import android.os.Bundle;
  17. import android.os.Environment;
  18. import android.provider.MediaStore;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.widget.Button;
  22. import android.widget.ImageView;
  23. import android.widget.Toast;
  24.  
  25. import androidx.activity.result.ActivityResult;
  26. import androidx.activity.result.ActivityResultCallback;
  27. import androidx.activity.result.ActivityResultLauncher;
  28. import androidx.activity.result.contract.ActivityResultContracts;
  29. import androidx.annotation.NonNull;
  30. import androidx.appcompat.app.AppCompatActivity;
  31.  
  32. import java.io.File;
  33. import java.io.FileOutputStream;
  34. import java.util.Date;
  35. import java.util.Properties;
  36.  
  37. import javax.activation.DataHandler;
  38. import javax.activation.DataSource;
  39. import javax.activation.FileDataSource;
  40. import javax.mail.Authenticator;
  41. import javax.mail.Message;
  42. import javax.mail.MessagingException;
  43. import javax.mail.Multipart;
  44. import javax.mail.PasswordAuthentication;
  45. import javax.mail.Session;
  46. import javax.mail.Transport;
  47. import javax.mail.internet.AddressException;
  48. import javax.mail.internet.InternetAddress;
  49. import javax.mail.internet.MimeBodyPart;
  50. import javax.mail.internet.MimeMessage;
  51. import javax.mail.internet.MimeMultipart;
  52.  
  53. public class MainActivity extends AppCompatActivity {
  54.  
  55.     private static final int PERMISSION_CODE = 1000;
  56.     private static final int IMAGE_CAPTURE_CODE = 1001;
  57.     Button mCaptureBtn;
  58.     Button mSaveBtn;
  59.     ImageView mImageView;
  60.     Uri image_uri;
  61.     File duplicateFile;
  62.     Integer photoCompressionRate = 66;
  63.  
  64.     @Override
  65.     protected void onCreate(Bundle savedInstanceState) {
  66.         super.onCreate(savedInstanceState);
  67.         setContentView(R.layout.activity_main);
  68.  
  69.         mImageView = findViewById(R.id.image_view);
  70.         mCaptureBtn = findViewById(R.id.cameraButton);
  71.         mSaveBtn = findViewById(R.id.saveButton);
  72.  
  73.  
  74.         final String username = "adresse1";
  75.         final String password = "password";
  76.  
  77.         Properties props = new Properties();
  78.         props.put("mail.smtp.auth", "true");
  79.         props.put("mail.smtp.starttls.enable", "true");
  80.         props.put("mail.smtp.host", "smtp.free.fr");
  81.         props.put("mail.smtp.port", "587");
  82.  
  83.         Session session = Session.getInstance(props,
  84.                 new javax.mail.Authenticator() {
  85.                     protected PasswordAuthentication getPasswordAuthentication() {
  86.                         return new PasswordAuthentication(username, password);
  87.                     }
  88.                 });
  89.         try {
  90.             Message message = new MimeMessage(session);
  91.             message.setFrom(new InternetAddress("adresse1"));
  92.             message.setRecipients(Message.RecipientType.TO,
  93.                     InternetAddress.parse("adresse2"));
  94.             message.setSubject("Testing Subject");
  95.             message.setText("Dear Mail Crawler,"
  96.                     + "\n\n No spam to my email, please!");
  97.  
  98.             MimeBodyPart messageBodyPart = new MimeBodyPart();
  99.  
  100.             Multipart multipart = new MimeMultipart();
  101.  
  102.             messageBodyPart = new MimeBodyPart();
  103.             String file = "/storage/emulated/0/Pictures/";
  104.             String fileName = "1658652512673.jpg";
  105.             DataSource source = new FileDataSource(file);
  106.             messageBodyPart.setDataHandler(new DataHandler(source));
  107.             messageBodyPart.setFileName(fileName);
  108.             multipart.addBodyPart(messageBodyPart);
  109.  
  110.             message.setContent(multipart);
  111.  
  112.             Transport.send(message);
  113.  
  114.             System.out.println("Done");
  115.  
  116.         } catch (MessagingException e) {
  117.             throw new RuntimeException(e);
  118.         }
  119.  
  120.  
  121.         //SendMail();
  122.  
  123.         //try {
  124.         //    MailSender sender = new MailSender("adresse1", "password");
  125.         //    sender.sendMail("This is Subject",
  126.         //            "This is Body",
  127.         //            "adresse1",
  128.         //            "adresse2");
  129.         //} catch (Exception e) {
  130.         //    Log.e("SendMail", e.getMessage(), e);
  131.         //}
  132.  
  133.         //SendMail();
  134.  
  135.         //try {
  136.         //    sendEmail("adresse1", "adresse1", "PictGrabber dump", "The app just sent you a new picture", "/storage/emulated/0/DCIM/Camera/1658661160448.jpg");
  137.         //} catch (Exception e) {
  138.         //    e.printStackTrace();
  139.         //}
  140.  
  141.         mCaptureBtn.setOnClickListener(new View.OnClickListener() {
  142.             @Override
  143.             public void onClick(View v) {
  144.                 //check os version and runtime permission
  145.                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  146.                     if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
  147.                             checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_DENIED ||
  148.                             checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ||
  149.                             checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_DENIED ||
  150.                             checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
  151.                         //permission not enabled, request it
  152.                         String[] permission = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
  153.                         //Show popup
  154.                         requestPermissions(permission, PERMISSION_CODE);
  155.                     } else {
  156.                         //permission already granted
  157.                         openCamera();
  158.                     }
  159.                 } else {
  160.                     //system OS recent enough
  161.                     openCamera();
  162.                 }
  163.             }
  164.         });
  165.  
  166.         mSaveBtn.setOnClickListener(new View.OnClickListener() {
  167.             @Override
  168.             public void onClick(View v) {
  169.                 BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
  170.                 Bitmap bitmap = drawable.getBitmap();
  171.                 try {
  172.                     String root = Environment.getExternalStorageDirectory().toString();
  173.                     String filename = String.format("%d.jpg", System.currentTimeMillis());
  174.                     File file = new File(root + "/DCIM/Camera/" + filename);
  175.                     FileOutputStream out = new FileOutputStream(file);
  176.                     bitmap.compress(Bitmap.CompressFormat.JPEG, photoCompressionRate, out);
  177.                     out.flush();
  178.                     out.close();
  179.                     MediaScannerConnection.scanFile(MainActivity.this,
  180.                             new String[]{file.toString()}, null,
  181.                             new MediaScannerConnection.OnScanCompletedListener() {
  182.                                 public void onScanCompleted(String path, Uri uri) {
  183.                                     Log.i("ExternalStorage", "Scanned " + path + ":");
  184.                                     Log.i("ExternalStorage", "-> uri=" + uri);
  185.                                 }
  186.                             });
  187.                     cleanPictureGenerated();
  188.                     //Intent i = new Intent(Intent.ACTION_SEND);
  189.                     //i.putExtra(Intent.EXTRA_EMAIL, new String[]{"adresse1"});
  190.                     //i.putExtra(Intent.EXTRA_SUBJECT,"PictGrabber saved picture");
  191.                     //i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
  192.                     //i.setType("image/png");
  193.                     //startActivity(Intent.createChooser(i,"Send mail"));
  194.                     Toast.makeText(MainActivity.this, "Picture saved", Toast.LENGTH_SHORT).show();
  195.  
  196.                 } catch (Exception ex) {
  197.                     ex.printStackTrace();
  198.                 }
  199.             }
  200.         });
  201.     }
  202.  
  203.     private void openCamera() {
  204.         ContentValues values = new ContentValues();
  205.         values.put(MediaStore.Images.Media.TITLE, "New Picture");
  206.         values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
  207.         image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
  208.  
  209.         //Camera intent
  210.         Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  211.         cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
  212.         //startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
  213.         //startActivity(cameraIntent);
  214.         someActivityResultLauncher.launch(cameraIntent);
  215.     }
  216.  
  217.     //handling permission result
  218.     @SuppressLint("MissingSuperCall")
  219.     @Override
  220.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  221.         //this method is called when user press Allow or Deny from Permission Request Popup
  222.         switch (requestCode) {
  223.             case PERMISSION_CODE: {
  224.                 if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  225.                     //permission from popup was granted
  226.                     openCamera();
  227.                 } else {
  228.                     //permission from popup was denied
  229.                     Toast.makeText(this, "Permission denied...", Toast.LENGTH_SHORT).show();
  230.                 }
  231.             }
  232.         }
  233.     }
  234.  
  235.     ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
  236.             new ActivityResultContracts.StartActivityForResult(),
  237.             new ActivityResultCallback<ActivityResult>() {
  238.                 @Override
  239.                 public void onActivityResult(ActivityResult result) {
  240.                     if (result.getResultCode() == Activity.RESULT_OK) {
  241.                         //Intent data = result.getData();
  242.                         mImageView.setImageURI(image_uri);
  243.                     }
  244.                 }
  245.             });
  246.  
  247.     private void cleanPictureGenerated() {
  248.         String path = Environment.getExternalStorageDirectory().toString() + "/Pictures";
  249.         Log.d("======> Files", "Path: " + path);
  250.         File directory = new File(path);
  251.         File[] files = directory.listFiles();
  252.         Log.d("======> Files", "Size: " + files.length);
  253.         Date trueLastModDate = null;
  254.         for (int i = 0; i < files.length; i++) {
  255.             if (files[i].isFile()) {
  256.                 if (trueLastModDate == null) {
  257.                     trueLastModDate = new Date(files[i].lastModified());
  258.                 } else {
  259.                     Date lastModDate = new Date(files[i].lastModified());
  260.                     if (lastModDate.compareTo(trueLastModDate) > 0) {
  261.                         trueLastModDate = lastModDate;
  262.                     }
  263.                 }
  264.             }
  265.         }
  266.         for (int i = 0; i < files.length; i++) {
  267.             if (files[i].isFile()) {
  268.                 Date lastModDate = new Date(files[i].lastModified());
  269.                 if (lastModDate.compareTo(trueLastModDate) == 0) {
  270.                     Log.d("======> Files", "Filename deleted: " + files[i].getName() + " - Last mod date: " + trueLastModDate.toString());
  271.                     files[i].delete();
  272.                 }
  273.             }
  274.         }
  275.     }
  276.  
  277.     //public static boolean sendEmail(String to, String from, String subject, String message, String attachement) throws Exception {
  278.     //    Mail mail = new Mail();
  279.     //    if (subject != null && subject.length() > 0) {
  280.     //        mail.setSubject(subject);
  281.     //    } else {
  282.     //        mail.setSubject("Subject");
  283.     //    }
  284. //
  285.     //    if (message != null && message.length() > 0) {
  286.     //        mail.setBody(message);
  287.     //    } else {
  288.     //        mail.setBody("Message");
  289.     //    }
  290. //
  291.     //    mail.setTo(new String[] {to});
  292. //
  293.     //    if (attachement != null) {
  294.     //        mail.addAttachment(attachement);
  295.     //    }
  296.     //    return mail.send();
  297.     //}
  298.  
  299.  
  300.     public void SendMail (){
  301.  
  302.         try {
  303.             String stringSenderEmail = "adresse1"; //"adresse1";
  304.             String stringReceiverEmail = "adresse2";
  305.             String stringPasswordSenderEmail = "password"; //"upmbksrwnxqzfqtn";
  306.  
  307.             String stringHost = "smtp.free.fr"; //"212.27.48.4"; //"smtp.free.fr"; //"smtp.gmail.com";
  308.  
  309.             Properties properties = System.getProperties();
  310.  
  311.             properties.put("mail.smtp.host", stringHost);
  312.             properties.put("mail.smtp.port", "465");
  313.             properties.put("mail.smtp.ssl.enable", "true");
  314.             //properties.put("mail.smtp.socketFactory.port", "465");
  315.             //properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  316.             properties.put("mail.smtp.auth", "true");
  317.  
  318.             javax.mail.Session session = Session.getInstance(properties, new Authenticator() {
  319.                 @Override
  320.                 protected PasswordAuthentication getPasswordAuthentication() {
  321.                     return new PasswordAuthentication(stringSenderEmail, stringPasswordSenderEmail);
  322.                 }
  323.             });
  324.  
  325.             MimeMessage mimeMessage = new MimeMessage(session);
  326.             mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(stringReceiverEmail));
  327.  
  328.             mimeMessage.setSubject("Subject: Android App email");
  329.             mimeMessage.setText("Hello Programmer, \n\nProgrammer World has sent you this 2nd email. \n\n Cheers!\nProgrammer World");
  330.  
  331.             try {
  332.                 Transport.send(mimeMessage);
  333.             } catch (MessagingException e) {
  334.                 e.printStackTrace();
  335.             }
  336.             //Thread thread = new Thread(new Runnable() {
  337.             //    @Override
  338.             //    public void run() {
  339.             //        try {
  340.             //            Transport.send(mimeMessage);
  341.             //        } catch (MessagingException e) {
  342.             //            e.printStackTrace();
  343.             //        }
  344.             //    }
  345.             //});
  346.             //thread.start();
  347.  
  348.         } catch (AddressException e) {
  349.             e.printStackTrace();
  350.         } catch (MessagingException e) {
  351.             e.printStackTrace();
  352.         }
  353.     }
  354. }
  355.  
  356. ------------------------------AndroidManifest.xml
  357. <?xml version="1.0" encoding="utf-8"?>
  358. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  359.     xmlns:tools="http://schemas.android.com/tools"
  360.     package="com.example.testactivity">
  361.  
  362.     <uses-permission android:name="android.permission.CAMERA" />
  363.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  364.     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  365.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  366.     <uses-permission android:name="android.permission.INTERNET" />
  367.     <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  368.     <uses-permission android:name="android.permission.USE_CREDENTIALS" />
  369.  
  370.  
  371.     <application
  372.         android:allowBackup="true"
  373.         android:dataExtractionRules="@xml/data_extraction_rules"
  374.         android:fullBackupContent="@xml/backup_rules"
  375.         android:label="@string/app_name"
  376.         android:icon="@drawable/ic_baseline_camera_alt_24"
  377.         android:roundIcon="@drawable/ic_baseline_camera_alt_24"
  378.         android:supportsRtl="true"
  379.         android:theme="@style/Theme.TestActivity"
  380.         tools:targetApi="31">
  381.         <activity
  382.             android:name=".MainActivity"
  383.             android:label="Picture grabber"
  384.             android:screenOrientation="landscape"
  385.             android:exported="true">
  386.             <intent-filter>
  387.                 <action android:name="android.intent.action.MAIN" />
  388.  
  389.                 <category android:name="android.intent.category.LAUNCHER" />
  390.             </intent-filter>
  391.         </activity>
  392.     </application>
  393.  
  394. </manifest>
  395.  
  396. ------------------------------activity_main.xml
  397. <?xml version="1.0" encoding="utf-8"?>
  398. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  399.     xmlns:app="http://schemas.android.com/apk/res-auto"
  400.     xmlns:tools="http://schemas.android.com/tools"
  401.     android:layout_width="match_parent"
  402.     android:layout_height="match_parent"
  403.     tools:context=".MainActivity">
  404.  
  405.     <!--Image view in which image will be set -->
  406.  
  407.     <ImageView
  408.         android:id="@+id/image_view"
  409.         android:layout_width="0dp"
  410.         android:layout_height="0dp"
  411.         android:src="@drawable/ic_baseline_image_24"
  412.         app:layout_constraintBottom_toTopOf="@+id/cameraButton"
  413.         app:layout_constraintEnd_toEndOf="parent"
  414.         app:layout_constraintHorizontal_bias="0.0"
  415.         app:layout_constraintStart_toStartOf="parent"
  416.         app:layout_constraintTop_toTopOf="parent" />
  417.  
  418.     <Button
  419.         android:id="@+id/cameraButton"
  420.         android:layout_width="372dp"
  421.         android:layout_height="82dp"
  422.         android:layout_marginStart="52dp"
  423.         android:backgroundTint="#A32E2E"
  424.         android:text="Take picture"
  425.         app:layout_constraintBottom_toBottomOf="parent"
  426.         app:layout_constraintStart_toStartOf="@+id/image_view"
  427.         app:layout_constraintTop_toBottomOf="@+id/image_view" />
  428.  
  429.     <Button
  430.         android:id="@+id/saveButton"
  431.         android:layout_width="176dp"
  432.         android:layout_height="78dp"
  433.         android:layout_marginStart="128dp"
  434.         android:layout_marginBottom="4dp"
  435.         android:backgroundTint="#A32E2E"
  436.         android:text="Save"
  437.         app:layout_constraintBottom_toBottomOf="parent"
  438.         app:layout_constraintStart_toEndOf="@+id/cameraButton" />
  439.  
  440. </androidx.constraintlayout.widget.ConstraintLayout>
  441.  
  442.  
  443.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement