I am working on QR code scanner App which takes user credentials and scan QR code and store User credentials with the content on QR code.
Since, I am beginner on working with Android App Development and hence, facing several issues such as:
(i) While opening camera permissions in App, it doesn't start automatically.I need to restart the app to open the camera to start QR code scanning.
Is there any possibility through which my app opens camera without taking permission from user. I have seen many apps doing so.
Or is there any modifications I can do to my QR scanner Java file so my camera works on runtime permission :qrscan.java
package com.example.android.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.android.loginapp.R;
import com.google.android.gms.common.wrappers.PackageManagerWrapper;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class qrscan extends AppCompatActivity {
private Button takePictureButton;
SurfaceView surfaceView;
CameraSource cameraSource;
TextView textView;
BarcodeDetector barcodeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.qrcode);
super.onCreate(savedInstanceState);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
textView=(TextView)findViewById(R.id.textView);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this,barcodeDetector).setRequestedPreviewSize(640,480).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(qrscan.this, new String[] {Manifest.permission.CAMERA}, 0);
return;
}
try {
cameraSource.start(holder);
}catch(IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size()!=0){
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator=(Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}
});
}
}
(ii) My second issue is that: I want to store credentials of user with the QR code. But I lack knowledge of database and all those stuff.
Is there any easy way through which I can store such data ?
Something like storing data on google cloud.
I have already seen similar questions on stack overflow but none of them solves my issue.
This question is similar but doesn't help : surface view does not show camera after i gave permission
You need to check for permission to camera in activity where you have qr reader functionality before you start using it. If application do not have permission to that device you push it for ask again or just ignore it and let user know about it by message.
Example code
private void permissionAsk(String permission){
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
String permission = Manifest.permission.CAMERA;
permissionAsk(permission);
permissionAsk(Manifest.permission.RECORD_AUDIO);
permissionAsk(Manifest.permission.WRITE_EXTERNAL_STORAGE);
You can easly find more solutions like that almost ready to go.
Related
First of all this is not a duplicate of any other question on the site. I've seen location updates using Service and Google API both.
Here is the link which uses the service to get location updates
This is the link which uses Google API for the same. This works perfectly.
I've tried both, but in case of service, it is not working. But the 1st link's code is working perfectly fine, and gives location updates correctly. But I think It can't get update when the app is in background.
I want that code inside a service, which can continuously get location updates even my app is in background.
But can't figure out how to merge this two codes. If you are asking what I've tried? Than I've just copy the common methods in the service class. But it gives me too many errors :(
If there are alternative available for this please suggest me. I'm new to android.
Thanks in advance!
Try:
Service.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"GoogleApiClient connection has been suspend",Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"GoogleApiClient connection has failed",Toast.LENGTH_LONG).show();
}
and MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,GPSService.class);
startService(i);
}
I'm creating an app that I want to stream my foscam live feed in. I'm pretty new to coding and some of this code is over my head. I found some help getting this far but now am hitting a snag. The app runs but only displays a black screen. I believe i have the manifest and XML code all correct. The problem lies in my code. I hope someone can help me out
package com.rednak.camerastream;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity
implements MediaPlayer.OnPreparedListener,
SurfaceHolder.Callback {
final static String USERNAME = "guest";
final static String PASSWORD = "Guest";
final static String RTSP_URL = "rtsp://http://rednak71.ddns.net:8090/live1.sdp";
private MediaPlayer _mediaPlayer;
private SurfaceHolder _surfaceHolder;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up a full-screen black window.
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = getWindow();
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.setBackgroundDrawableResource(android.R.color.black);
setContentView(R.layout.activity_main);
// Configure the view that renders live video.
SurfaceView surfaceView =
(SurfaceView) findViewById(R.id.surfaceView);
_surfaceHolder = surfaceView.getHolder();
_surfaceHolder.addCallback(this);
_surfaceHolder.setFixedSize(320, 240);
}
// More to come…
/*
SurfaceHolder.Callback
*/
#
Override
public void surfaceChanged(
SurfaceHolder sh, int f, int w, int h) {}
#
Override
public void surfaceCreated(SurfaceHolder sh) {
_mediaPlayer = new MediaPlayer();
_mediaPlayer.setDisplay(_surfaceHolder);
Context context = getApplicationContext();
Map headers = getRtspHeaders();
Uri source = Uri.parse(RTSP_URL);
try {
// Specify the IP camera’s URL and auth headers.
_mediaPlayer.setDataSource(context, source, headers);
// Begin the process of setting up a video stream.
_mediaPlayer.setOnPreparedListener(this);
_mediaPlayer.prepareAsync();
} catch (Exception e) {}
}
#
Override
public void surfaceDestroyed(SurfaceHolder sh) {
_mediaPlayer.release();
}
private Map getRtspHeaders() {
Map headers = new HashMap();
String basicAuthValue = getBasicAuthValue(USERNAME, PASSWORD);
headers.put("Authorization", basicAuthValue);
return headers;
}
private String getBasicAuthValue(String usr, String pwd) {
String credentials = usr + ":" + pwd;
int flags = Base64.URL_SAFE | Base64.NO_WRAP;
byte[] bytes = credentials.getBytes();
return "Basic" + Base64.encodeToString(bytes, flags);
}
/*
MediaPlayer.OnPreparedListener
*/
#
Override
public void onPrepared(MediaPlayer mp) {
_mediaPlayer.start();
}
}
Make sure that Android's MediaPlayer can actually open and decode your stream. Right now, if the MediaPlayer cannot handle your stream, you are catching any exception and silently ignoring it:
try {
// Specify the IP camera’s URL and auth headers.
_mediaPlayer.setDataSource(context, source, headers);
// Begin the process of setting up a video stream.
_mediaPlayer.setOnPreparedListener(this);
_mediaPlayer.prepareAsync();
} catch (Exception e) {}
At the very least you should log the error:
} catch (Exception e) {
Log.e("MyApp", "Could not open data source", e);
}
Although the MediaPlayer service will most likely pepper the log with its own errors. So what you should do is review the logcat for any messages from the "VideoDecoder" or similar.
To see the logcat in Android Studio, open the "Android Monitor" tab which is on the bottom by default. If you want to see the unfiltered logcat make sure that in the top-right corner of the Android Monitor view it says "No Filters" instead of "Show only selected application".
I have some new code that links to the Foscam videostream but only grabs the frame when it starts then does not stream. Im closer but still need help. Am i on the right track here?
package com.rednak.camstream;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.VideoView;
public class MainCamActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cam);
VideoView vidView = (VideoView)findViewById(R.id.CamVideoView);
String vidAddress = "http://rednak71.ddns.net:8090/CGIProxy.fcgi? cmd=snapPicture2&usr=guest&pwd=guest&t=";
Uri vidUri = Uri.parse(vidAddress);
vidView.setVideoURI(vidUri);
vidView.start();
}
}
(Background: all I want is a unique and persistent Google Play identifier for the user. (even after uninstalls, or on different devices) This is the only reason I am doing this.)
I am using Cordova. This is my main activity.
Problem: the onConnected function never runs. I am able to sign in fine, however. (I can see the sign in window, the sign in circle, and everything else) but it just never runs.
NOTE: onConnectionFailed runs once, with a SIGN_IN_REQUIRED statusCode.
package com.myapp;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.games.Players;
import com.google.android.gms.games.Games;
import android.os.Bundle;
import org.apache.cordova.*;
import android.util.Log;
public class MyApp extends CordovaActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String LOGTAG = "GooglePlayServices";
// Client used to interact with Google APIs.
private GoogleApiClient mGoogleApiClient;
private CordovaActivity activity;
boolean mResolvingError;
#Override public void onCreate (Bundle savedInstanceState) {
activity = this;
super.onCreate (savedInstanceState);
super.init ();
mGoogleApiClient = new GoogleApiClient.Builder (this)
.addConnectionCallbacks (this)
.addOnConnectionFailedListener (this)
.addApi (Games.API)
.addScope(Games.SCOPE_GAMES)
.build ();
mGoogleApiClient.connect ();
super.loadUrl(Config.getStartUrl());
}
#Override public void onConnectionFailed (ConnectionResult result) {
if (mResolvingError) return;
if (!result.hasResolution()) {mResolvingError = true; return;}
Log.d (LOGTAG, result.toString());
try {
mResolvingError = true;
result.startResolutionForResult (this, result.getErrorCode());
} catch (SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect ();
}
}
#Override public void onConnected (Bundle connectionHint) {
// This never runs... this is the most critical part. I need the player ID!
String playerId = Games.Players.getCurrentPlayerId (mGoogleApiClient);
Log.w (LOGTAG, playerId);
}
// I saw this one with an #Override in others' code, but it won't compile if I add that.
public void onDisconnected () {}
protected void onStart () {super.onStart (); mGoogleApiClient.connect ();}
protected void onStop () {
super.onStop ();
if (mGoogleApiClient.isConnected()) mGoogleApiClient.disconnect ();
}
protected void onActivityResult (int requestCode, int responseCode, Intent intent) {
if (!mGoogleApiClient.isConnecting()) mGoogleApiClient.connect ();
}
public void onConnectionSuspended (int cause) {mGoogleApiClient.connect ();}
}
"Your Oauth2 client CAN NOT be created from Google APIs Console, it MUST be created from the Google Play UI."
I'm new to Java, Android and JUnit. I want to learn how to write JUnit tests for an Android application. To that end, I have a very simple Android app (2 activities, 2 buttons, each button goes to the other activity). I want to test the button. This app runs fine on my phone when it's plugged in. I've been looking at the samples provided in the SDK, and I am trying to emulate them.
My problem is that when I right-click on my test project, and choose Run As -> Android JUnit test, nothing happens. I don't know why.
My test code.
package com.example.twoactivities.test;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import com.example.twoactivities.MainActivity;
import com.example.twoactivities.MainActivity2;
public class ClickButton extends ActivityInstrumentationTestCase2<MainActivity> {
private Button mButton2;
private long TIMEOUT_IN_MS = 100000;
public ClickButton() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
final MainActivity a = getActivity();
// ensure a valid handle to the activity has been returned
assertNotNull(a);
}
#SmallTest
public void click(){
// Set up an ActivityMonitor
ActivityMonitor activityMonitor = getInstrumentation().addMonitor(MainActivity2.class.getName(), null, false);
//check if button is enabled
assertTrue("button is enabled", mButton2.isEnabled());
//click button
mButton2.performClick();
MainActivity2 MainActivity2 = (MainActivity2) activityMonitor.waitForActivityWithTimeout(TIMEOUT_IN_MS );
assertNotNull("MainActivity2 is null", MainActivity2);
// assertEquals("Monitor for MainActivity2 has not been called", 1, activityMonitor.getHits());
// assertEquals("Activity is of wrong type", MainActivity2.class, MainActivity2.getClass());
// Remove the ActivityMonitor
getInstrumentation().removeMonitor(activityMonitor);
}
// public void tearDown() {
// }
}
(I know it's really simple, but I'm just trying to get the basics down.)
My application.
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
}
Activity 2 of my application.
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void activity1(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity.class);
startActivity(intent);
}
}
Any ideas why my test class doesn't run?
Thanks,
Stephanie
You have to right click on the test itself, not the project.
According to documentation Android testing API supports JUnit 3 code style, but not JUnit 4. Try naming your test method testClick
So I've got a small problem which is doing my head in. I do know that the solution is something obvious and simple, but I'm new to programming and can't seem to get my head around it.
Basically, I've been following a Flashlight tutorial using Android Studio. In the tutorial, they used a simple button that would toggle into Flashlight ON, and Flashlight OFF modes.
I did not want to use just a button, and instead wanted to use an ImageButton instead, taking up the entire screen, and the clicking of the image would turn on the flashlight and change the image.
So, I simply modified the code after the flash would turn on into a setImageResource change. But clicking the image crashes the app rightaway unfortunately :(
Hope someone can help a noob out! Below is my Main Java file.
package com.dbz.flash;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
private boolean isFlashOn = false;
private Camera camera;
private ImageButton btnSwitch;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",
Toast.LENGTH_SHORT).show();
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
btnSwitch.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
//button.setText("Torch-ON");
btnSwitch.setImageResource(R.drawable.off);
} else {
Log.i("info", "torch is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
//button.setText("Torch-OFF");
btnSwitch.setImageResource(R.drawable.on);
}
}
});
}
}
`