Make QR scanner separate activity and get code using activity result

This commit is contained in:
Garrett Mills 2021-05-12 12:07:07 -05:00
parent 3cc9031a8e
commit d73c79f083
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246
8 changed files with 170 additions and 114 deletions

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@ -1,6 +1,5 @@
plugins { plugins {
id 'com.android.application' id 'com.android.application'
// id 'kotlin-android-extensions'
} }
android { android {

View File

@ -3,6 +3,7 @@
package="dev.garrettmills.starship.hyperlink"> package="dev.garrettmills.starship.hyperlink">
<uses-feature android:name="android.hardware.camera.any" /> <uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<application <application
@ -12,6 +13,7 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.StarshipHyperlink"> android:theme="@style/Theme.StarshipHyperlink">
<activity android:name=".LoginTokenScannerActivity"></activity>
<activity android:name=".MainActivity"> <activity android:name=".MainActivity">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />

View File

@ -3,9 +3,14 @@ package dev.garrettmills.starship.hyperlink;
import android.content.SharedPreferences; import android.content.SharedPreferences;
public class Hyperlink { public class Hyperlink {
public static final String SHARED_PREFERENCES_NAME = "hyperlink.main"; public static final int PERMISSION_REQUEST_CAMERA = 0;
public static final String SERVER_ADDR = "hyperlink.server"; public static final String SHARED_PREFERENCES_NAME = "dev.garrettmills.starship.hyperlink.main";
public static final String SERVER_TOKEN = "hyperlink.token.server"; public static final String SERVER_ADDR = "dev.garrettmills.starship.hyperlink.server";
public static final String SERVER_TOKEN = "dev.garrettmills.starship.hyperlink.token.server";
public static final String EXTRA_LOGIN_TOKEN = "dev.garrettmills.starship.hyperlink.extra.login_token";
public static final int REQUEST_LOGIN_TOKEN = 180;
public static SharedPreferences preferences; public static SharedPreferences preferences;
} }

View File

@ -0,0 +1,114 @@
package dev.garrettmills.starship.hyperlink;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Size;
import android.widget.Toast;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
import dev.garrettmills.starship.hyperlink.scanner.QRCodeImageAnalyzer;
import dev.garrettmills.starship.hyperlink.scanner.QRCodeListener;
public class LoginTokenScannerActivity extends AppCompatActivity implements QRCodeListener {
private PreviewView previewView;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private String qrCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_token_scanner);
previewView = findViewById(R.id.activity_login_token_scanner_previewView);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
requestCamera();
}
protected void requestCamera() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Hyperlink.PERMISSION_REQUEST_CAMERA);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Hyperlink.PERMISSION_REQUEST_CAMERA);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == Hyperlink.PERMISSION_REQUEST_CAMERA) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
Toast.makeText(this, "Camera Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void startCamera() {
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindCameraPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
Toast.makeText(this, "Error starting camera: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}, ContextCompat.getMainExecutor(this));
}
private void bindCameraPreview(@NonNull ProcessCameraProvider cameraProvider) {
previewView.setPreferredImplementationMode(PreviewView.ImplementationMode.SURFACE_VIEW);
Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
preview.setSurfaceProvider(previewView.createSurfaceProvider());
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), new QRCodeImageAnalyzer(this));
Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, imageAnalysis, preview);
}
public void onQRCodeFound(String qrCode) {
if ( !isValidLoginToken(qrCode) ) return;
Intent result = new Intent();
result.putExtra(Hyperlink.EXTRA_LOGIN_TOKEN, qrCode);
setResult(RESULT_OK, result);
finish();
}
public void onQRCodeNotFound() {}
public boolean isValidLoginToken(String token) {
return true;
}
}

View File

@ -1,126 +1,34 @@
package dev.garrettmills.starship.hyperlink; package dev.garrettmills.starship.hyperlink;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.Manifest; import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import android.view.View; import android.view.View;
import android.widget.Button;
import android.widget.Toast; import android.widget.Toast;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
import dev.garrettmills.starship.hyperlink.scanner.QRCodeImageAnalyzer;
import dev.garrettmills.starship.hyperlink.scanner.QRCodeListener;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CAMERA = 0;
private PreviewView previewView;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private Button qrCodeFoundButton;
private String qrCode;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Hyperlink.preferences = getSharedPreferences(Hyperlink.SHARED_PREFERENCES_NAME, MODE_PRIVATE); Hyperlink.preferences = getSharedPreferences(Hyperlink.SHARED_PREFERENCES_NAME, MODE_PRIVATE);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
previewView = findViewById(R.id.activity_main_previewView);
qrCodeFoundButton = findViewById(R.id.activity_main_qrCodeFoundButton);
qrCodeFoundButton.setVisibility(View.INVISIBLE);
qrCodeFoundButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), qrCode, Toast.LENGTH_LONG).show();
Log.i(MainActivity.class.getSimpleName(), "QR Code Found: " + qrCode);
}
});
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
requestCamera();
} }
protected void requestCamera() { public void onScanTokenClick(View view) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(this, LoginTokenScannerActivity.class);
startCamera(); startActivityForResult(intent, Hyperlink.REQUEST_LOGIN_TOKEN);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
}
}
} }
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PERMISSION_REQUEST_CAMERA) { super.onActivityResult(requestCode, resultCode, data);
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startCamera(); if ( resultCode == RESULT_OK && requestCode == Hyperlink.REQUEST_LOGIN_TOKEN ) {
} else { if ( data.hasExtra(Hyperlink.EXTRA_LOGIN_TOKEN) ) {
Toast.makeText(this, "Camera Permission Denied", Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), data.getExtras().getString(Hyperlink.EXTRA_LOGIN_TOKEN), Toast.LENGTH_SHORT).show();
} }
} }
} }
private void startCamera() {
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindCameraPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
Toast.makeText(this, "Error starting camera: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}, ContextCompat.getMainExecutor(this));
}
private void bindCameraPreview(@NonNull ProcessCameraProvider cameraProvider) {
previewView.setPreferredImplementationMode(PreviewView.ImplementationMode.SURFACE_VIEW);
Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
preview.setSurfaceProvider(previewView.createSurfaceProvider());
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), new QRCodeImageAnalyzer(new QRCodeListener() {
@Override
public void onQRCodeFound(String _qrCode) {
qrCode = _qrCode;
qrCodeFoundButton.setVisibility(View.VISIBLE);
}
@Override
public void onQRCodeNotFound() {
qrCodeFoundButton.setVisibility(View.INVISIBLE);
}
}));
Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, imageAnalysis, preview);
}
} }

View File

@ -0,0 +1,24 @@
<?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">
<androidx.camera.view.PreviewView
android:id="@+id/activity_login_token_scanner_previewView"
android:layout_width="match_parent"
android:layout_height="match_parent"></androidx.camera.view.PreviewView>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan the login QR code generated in the Hyperlink web app."
android:textAlignment="center"
android:translationY="-150dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -6,18 +6,16 @@
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity"> tools:context=".MainActivity">
<androidx.camera.view.PreviewView
android:id="@+id/activity_main_previewView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button <Button
android:id="@+id/activity_main_qrCodeFoundButton" android:id="@+id/activity_main_qrCodeFoundButton"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="QR Code Found" android:onClick="onScanTokenClick"
app:layout_constraintBottom_toBottomOf="@+id/activity_main_previewView" android:text="Scan QR Code"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/> app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>