I went through the other SO posts but didn't find anything relevant to my problem.
I am trying to create an app that will get the user's step count from the last reboot. Here is my main Activity:
package com.assignment.bwowassignment;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements MainActivityContract.View {
MainActivityPresenter presenter;
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d("mihir", "hello");
presenter = new MainActivityPresenter(this);
presenter.requestActivityPermission(this);
}
#Override
public void onGetStepsSuccess(float[] values) {
Log.d("mihir", Arrays.toString(values));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == presenter.ACTIVITY_REQUEST_CODE)
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
presenter.registerListener(this);
else {
Log.d("mihir", "kill me");
finish();
}
}
#Override
protected void onPause() {
super.onPause();
presenter.sensorManager.unregisterListener(presenter);
}
}
MainActivityPresenter.java
package com.assignment.bwowassignment;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.logging.Logger;
public class MainActivityPresenter implements MainActivityContract.Presenter, SensorEventListener {
MainActivityContract.View view;
SensorManager sensorManager;
Sensor sensor;
public MainActivityPresenter(MainActivityContract.View view) {
this.view = view;
sensorManager = (SensorManager) ((Context) view).getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}
#Override
public void registerListener(Context context) {
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void requestActivityPermission(Context context) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED)
registerListener(context);
else if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACTIVITY_RECOGNITION))
new AlertDialog.Builder(context)
.setTitle("Permission required")
.setMessage("This permission is required to fetch the sensor data from your phone, denying it will cause the app to exit")
.setPositiveButton("Give permission", (dialog, which) -> ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, ACTIVITY_REQUEST_CODE))
.setNegativeButton("Deny", (dialog, which) -> ((Activity) context).finish())
.show();
else
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, ACTIVITY_REQUEST_CODE);
}
#Override
public void onSensorChanged(SensorEvent event) {
view.onGetStepsSuccess(event.values);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
MainActivityContract.java
package com.assignment.bwowassignment;
import android.content.Context;
public interface MainActivityContract {
interface View {
void onGetStepsSuccess(float[] values);
}
interface Presenter {
int ACTIVITY_REQUEST_CODE = 1;
void registerListener(Context context);
void requestActivityPermission(Context context);
}
}
As you can see there are two Logs with my name in the tag, what is happening here is the "hello" log is getting logged twice. I am guessing it's the first onCreate which is responsible for my app finishing before starting since I get this warning in the logcat:
W/Activity: Can request only one set of permissions at a time
I am only requesting one permission but due to the onCreate being called twice the first permission gets automatically denied which causes the app to finish() before it already started! I have been scratching my head over this since yesterday, any help is appreciated!
I figured it out!
The culprit was this line:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
So apparently, this causes a configuration change, causing the onCreate method to be called twice, to get over this, call it BEFORE the call to super in onCreate like this:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Related
I am trying to ask for Device permission Upfront on app Launch to no avail. I am not using any Libraries since I am following this document(https://developer.android.com/training/permissions/requesting)
and I am intending to use it, What am I doing wrong?
Here is my Manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
This is my what I have tried on MainActivity and my minSdkVersion is 26
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_CODE = 100;
private Activity mActivity;
private Context mContext;
String[] appPermissions = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActivity = MainActivity.this;
mContext = getApplicationContext();
requestAppPermissions();
}
private void requestAppPermissions() {
try {
if(ContextCompat.checkSelfPermission(
mActivity,Manifest.permission.ACCESS_FINE_LOCATION
)+ContextCompat.checkSelfPermission(
mActivity,Manifest.permission.ACCESS_COARSE_LOCATION
)== PackageManager.PERMISSION_GRANTED
){
///perform action
Toast.makeText(mContext,"Permissions already granted",Toast.LENGTH_SHORT).show();
}else {
if (
//Do something when permission is not granted
ActivityCompat.shouldShowRequestPermissionRationale(
mActivity, Manifest.permission.ACCESS_FINE_LOCATION
) || ActivityCompat.shouldShowRequestPermissionRationale(
mActivity, Manifest.permission.ACCESS_COARSE_LOCATION
)
) {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setMessage("Location Permission is required by App.");
builder.setTitle("Please grant location Permission");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(
mActivity, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
},
REQUEST_CODE
);
}
});
builder.setNeutralButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE:{
if(
(
grantResults.length>0)&&(
grantResults[0]+grantResults[1]
==PackageManager.PERMISSION_GRANTED
)
){
Toast.makeText(mContext,"Permissions granted.",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mContext,"Permissions Denied.",Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}
I am planning on implementing ocr, the idea is for the user to capture an image and the app will write it as text to a file on the phone. I have managed to display the feed from the camera to the javacameraview using CvCameraViewListener2.
I now want to capture the frame as an Mat object and pass it to a new activity. The solution's I saw all involve saving the photo, or displaying the processed image or live processing. I just need to pass the Mat to another class for processing then I can release it. I'm having trouble find a methodology for doing this though it seems as though it should be fairly straightforward.
The question is essentially how to get the Mat object from the cameraview?
Any help or direction would be greatly appreciated.
Thank you stackoverflow
The relevant code is here
import android.Manifest;
import android.content.Intent;
Import android.content.pm.ActivityInfo; importandroid.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION_RESULT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation != 90) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.cameraInit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//marshmallow permissions
takePhoto();
}
});
}
private void callCamera(){
Intent startCameraIntent = new Intent(getApplicationContext(), OpenCVCamera.class);
startActivity(startCameraIntent);
}
public void takePhoto() {
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this, "This app requires camera access", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT);
}
} else {
callCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == REQUEST_CAMERA_PERMISSION_RESULT){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
callCamera();
} else {
Toast.makeText(this, "Permission Denied.", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.WindowManager;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
public class OpenCVCamera extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
// need to correct view size (i think this can be done in the xml
// else refer to cmaera video app
// also orientation needs to be corrected
private static final String TAG = "OpenCVCamera";
private CameraBridgeViewBase cameraBridgeViewBase;
private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
cameraBridgeViewBase.enableView();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_open_cvcamera);
cameraBridgeViewBase = (CameraBridgeViewBase) findViewById(R.id.camera_view);
cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE);
cameraBridgeViewBase.setCvCameraViewListener(this);
}
#Override
public void onResume(){
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, baseLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
baseLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
#Override
public void onCameraViewStarted(int width, int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
//original just returns inputFrame.rgba()
Core.rotate(inputFrame.rgba(), inputFrame.rgba(), Core.ROTATE_90_CLOCKWISE); //ROTATE_180 or ROTATE_90_COUNTERCLOCKWISE
return inputFrame.rgba();
}
}
i tried for hours to get my location,but that does not work...
i did it with a video guide step by step, the emulator is shot down while i run the application.
I already try lot of things like this solution.
And the GPS is enable in the virtual device... It's not working on my phone too. So this is my code
package com.example.idanhay.safebox;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class settings extends AppCompatActivity {
private Button button;
private TextView textView;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting2);
button = (Button) findViewById(R.id.bloc);
textView = (TextView) findViewById(R.id.tvloc);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("/n" + location.getAltitude() + "" + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(settings.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
}
} else
configurationButten();
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grandresult) {
switch (requestCode) {
case 10:
if (grandresult.length > 0 && grandresult[0] == PackageManager.PERMISSION_GRANTED)
configurationButten();
return;
}
}
private void configurationButten() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(settings.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
}
locationManager.requestLocationUpdates("gps", 4000, 0, locationListener);
}
});
/*
I want to set ZXingscanner as a content view inside my fragment, but it's not working. I have app with some tabs and on one of these tabs I want to have this ZXingscanner view, but when I try to set it it doesn't work.Isn't there any setContentView for fragment or something like that to work for this specific case ? And also Alert dialog builder shows error, it says alert dialog cannot be applied to fragment.Any help would be very helpful.
Here's the code:
package com.hist_area.imeda.histarea.fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class EmptyFragment extends Fragment implements ZXingScannerView.ResultHandler {
public static EmptyFragment create() {
return new EmptyFragment();
}
Vibrator vibrator;
private static final int CAMERA_PERMISSION_REQUEST_CODE = 8675309;
private ZXingScannerView mScannerView;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
invokecamera();
}
}
}
public void invokecamera() {
mScannerView = new ZXingScannerView(this);
return View(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void handleResult(Result result) {
vibrator.vibrate(369);
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mScannerView.resumeCameraPreview(EmptyFragment.this);
}
});
invokecamera();
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Hi im making an application using Android Studios the requires 3 permissions in total
CALL_PHONE, READ_CONTACTS, RECORD_AUDIO.
im kinda very new to development and thats why my coding is a bit sloppy(no kidding), when I run the app it doesnt asks for the permission and doesnt work but if i manually go to setting and grant the permissions it works fine
Im using fragments and writing the code in the fragment class is that wrong or should i write this code in my mainActivity.java
Im attaching both please look at my code and how can I improve it
If I have to work from the scratch im ok with it.
DialerActivity.java:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class DialerActivity extends FragmentActivity {
private static final String FRAGMENT_TAG_DIALER = "fragment:dialer";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialer);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (DialerFragment) fm.findFragmentByTag(FRAGMENT_TAG_DIALER);
if(fragment == null){
fragment = new DialerFragment();
fm.beginTransaction()
.add(R.id.fragment_container,fragment, FRAGMENT_TAG_DIALER)
.commit();
}
}
}
DialerFragmnet.java:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;;
import android.support.v4.content.ContextCompat;
public class DialerFragment extends Fragment {
private EditText mPhoneField;
private Button mDialButton;
//Requesting Permissions on Runtime.
final private int REQUEST_CODE_ASK_PERMISSIONS=0;
private void InitiateCall(){
int hasCallPermission = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE);
if (hasCallPermission != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
InitiateCall();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults ){
switch (requestCode){
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
//YAY! PERMISSION GRANTED
InitiateCall();
}else{
//GD! PERMISSION DENIED
Toast.makeText(getActivity(), R.string.permission_denied, Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View v=inflater.inflate(R.layout.fragment_dialer,container,false);
mPhoneField=(EditText) v.findViewById(R.id.input_pno);
mDialButton=(Button) v.findViewById(R.id.dial_button);
mDialButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
try{
if (mPhoneField != null && (mPhoneField.getText().length()==10||mPhoneField.getText().length()==11)){
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhoneField.getText())));
}
else if(mPhoneField != null && mPhoneField.getText().length()==0){
Toast.makeText(getActivity(),R.string.no_number_toast,Toast.LENGTH_SHORT).show();
}
else if(mPhoneField !=null && mPhoneField.getText().length()<10){
Toast.makeText(getActivity(),R.string.wrong_number_toast,Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
Log.e("DialerAppActivity","error: " + e.getMessage(),e);//Runtime error will be logged
}
}
});
return v;
}
}
You actually never call your method that ask the permission.
Your method : InitiateCall should not call itself, because it'll create an infiniteLoop. So you should modify it to be this way:
private void InitiateCall(){
int hasCallPermission = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE);
if (hasCallPermission != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
}
and you can call InitiateCall at the end of the onCreateView.