I am a beginner learning android development and I started learning about permissions but it is not working nor appearing in the emulator and when I go to the settings of the apps it is showing that there are no permissions asked for this app can anyone help me, please
the Actvity:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnOPenCamera;
private ImageView imgPhotoFromCamera;
private ConstraintLayout parent;
private static final int PERMISSION_REQUEST_CODE = 909;
private static final int OPEN_CAMERA_INTENT = 808;
private static final int OPEN_SETTINGS_INTENT = 707;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOPenCamera = findViewById(R.id.btnOPenCamera);
imgPhotoFromCamera = findViewById(R.id.imgPhotoFromCamera);
parent = findViewById(R.id.parent);
btnOPenCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handlePermession();
}
});
}
private void handlePermession(){
if (ActivityCompat.checkSelfPermission(this , Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "handlePermession: it is working");
openCamera();
}else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.CAMERA)){
showSnackBar();
}else{
Log.d(TAG, "handlePermession: it is working in the request");
ActivityCompat.requestPermissions(this , new String[] {Manifest.permission.CAMERA} , PERMISSION_REQUEST_CODE);
}
}
}
private void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent , OPEN_CAMERA_INTENT);
}
private void showSnackBar(){
Snackbar.make(parent , "This app need your permission to the camera" , BaseTransientBottomBar.LENGTH_INDEFINITE)
.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent , OPEN_SETTINGS_INTENT );
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case OPEN_CAMERA_INTENT:
if (resultCode == PackageManager.PERMISSION_GRANTED && data != null){
Bundle bundle = data.getExtras();
if (null != bundle){
Bitmap bitmap =(Bitmap) bundle.get("data");
imgPhotoFromCamera.setImageBitmap(bitmap);
}
}
break;
case OPEN_SETTINGS_INTENT:
handlePermession();
break;
default:
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}else{
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
and there are no errors in the logcat which is something confusing for me, Thanks
Your code seems to work for me. The only difference is that I have added the camera permission to the AndroidManifest.xml file
<manifest ...>
<uses-permission android:name="android.permission.CAMERA" />
...
<application ...>
...
</application>
</manifest>
Related
When I run an AlertDialog asking the user to get a photo from the camera or the gallery the program doesn't seem to wait for the results and continues to execute. This causes the result to not get saved properly into the Image View field. Ignore the unused variables as I am not done coding this activity yet. I am new to this so any other criticism is appreciated.
package ca.android.whitehead.mycardswallet;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
public class AddEditCardActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etCardName;
private ImageView ivCardFront, ivCardBack, ivBarcode;
private Button btnCardFront, btnCardBack, btnBarcode;
private Bitmap image;
private static final int SELECT_PHOTO = 1;
private static final int CAPTUR_PHOTO = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_card);
etCardName = findViewById(R.id.etCardName);
ivCardFront = findViewById(R.id.ivCardFront);
ivCardBack = findViewById(R.id.ivCardBack);
ivBarcode = findViewById(R.id.ivBarcode);
btnCardFront = findViewById(R.id.btnCardFront);
btnCardBack = findViewById(R.id.btnCardBack);
btnBarcode = findViewById(R.id.btnBarcode);
btnCardFront.setOnClickListener(this);
btnCardBack.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btnCardFront:
getImage();
if (image != null)
{
ivCardFront.setImageBitmap(image);
}
break;
case R.id.btnCardBack:
getImage();
if (image != null)
{
ivCardBack.setImageBitmap(image);
}
break;
}
}
public void getImage()
{
AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCardActivity.this);
builder.setTitle("Pick from gallery or take new picture");
Toast.makeText(this, "In Get Image", Toast.LENGTH_SHORT).show();
builder.setItems(R.array.uploadImage, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case 0:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PHOTO);
break;
case 1:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTUR_PHOTO);
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
if (resultData != null) {
// this is the image selected by the user
Uri imageUri = resultData.getData();
if (imageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
if (requestCode == CAPTUR_PHOTO && resultCode == RESULT_OK) {
if (resultData != null) {
// this is the image selected by the user
image = (Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data");
}
}
}
}
I ended up taking CommonsWare advice.
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
public class AddEditCardActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etCardName;
private ImageView ivCardFront, ivCardBack, ivBarcode;
private Button btnCardFront, btnCardBack, btnBarcode;
private Bitmap image;
private static final int SELECT_PHOTO = 100;
private static final int CAPTURE_PHOTO = 200;
private static final int FRONT_IMAGE = 1;
private static final int BACK_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_card);
etCardName = findViewById(R.id.etCardName);
ivCardFront = findViewById(R.id.ivCardFront);
ivCardBack = findViewById(R.id.ivCardBack);
ivBarcode = findViewById(R.id.ivBarcode);
btnCardFront = findViewById(R.id.btnCardFront);
btnCardBack = findViewById(R.id.btnCardBack);
btnBarcode = findViewById(R.id.btnBarcode);
btnCardFront.setOnClickListener(this);
btnCardBack.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btnCardFront:
getImage(1);
break;
case R.id.btnCardBack:
getImage(2);
break;
}
}
public void getImage(final int image)
{
AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCardActivity.this);
builder.setTitle("Pick from gallery or take new picture");
Toast.makeText(this, "In Get Image", Toast.LENGTH_SHORT).show();
builder.setItems(R.array.uploadImage, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case 0:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PHOTO + image);
break;
case 1:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_PHOTO + image);
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void setBitmap(Uri imageUri, ImageView imageView)
{
if (imageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
imageView.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(resultCode == RESULT_OK) {
if (requestCode == (SELECT_PHOTO + FRONT_IMAGE)) {
if (resultData != null) {
setBitmap(resultData.getData(), ivCardFront);
}
}
else if (requestCode == (SELECT_PHOTO + BACK_IMAGE)) {
if (resultData != null) {
setBitmap(resultData.getData(), ivCardBack);
}
}
else if (requestCode == CAPTURE_PHOTO + FRONT_IMAGE) {
if (resultData != null) {
// this is the image selected by the user
ivCardFront.setImageBitmap((Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data"));
}
}
else if (requestCode == CAPTURE_PHOTO + BACK_IMAGE) {
if (resultData != null) {
// this is the image selected by the user
ivCardBack.setImageBitmap((Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data"));
}
}
}
}
}
I am trying to check runtime permissions inside a fragment by calling permissions class but in fragment overided method to get result of permissions granted or not is not working in fragment
Here is method of class where i check or request permissions
public boolean checkPermissionForExternalStorage(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public void requestPermissionForExternalStorage(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
Here is my Fragment
package in.prsc.com.prscportal;
import android.Manifest;
import android.app.DownloadManager;
import android.app.Fragment;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
/**
* Created by Bhuvan on 05-Aug-16.
*/
public class LEP extends Fragment {
View myView;
ProgressBar pb;
WebView mWebView;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
public static int temp_perm;
MarshmallowPermissions marshmallowPermissions;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else
Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.web_front, container, false);
pb = (ProgressBar) myView.findViewById(R.id.progressBar);
mWebView = (WebView) myView.findViewById(R.id.webview);
marshmallowPermissions = new MarshmallowPermissions(getActivity());
if (Build.VERSION.SDK_INT >= 23) {
if (!marshmallowPermissions.checkPermissionForExternalStorage()) {
marshmallowPermissions.requestPermissionForExternalStorage();
}
}
return myView;
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MarshmallowPermissions.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Here i have to do my code after permissions granted
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
For Fragment, We have to pass Reference in Class
Create Constructor in MarshmallowPermissions Class
public MarshmallowPermissions(Context context, Fragment fragment) {
Log.e(TAG, "MarshMallowPermission() called with: " + "context = [" + context + "], activity = [" + fragment + "]");
this.fragment = fragment;
this.context = context;
}
public void requestPermissionForFragmentWriteExternalStorage() throws Exception {
try {
fragment.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public boolean checkPermissionForWriteExternalStorage() {
int result = context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
return false;
}
marshmallowPermissions = new MarshmallowPermissions(getActivity(),fragment);
I got the Answer
I tried and check permissions in my fragment instead of calling from other class and it works
Apply below code in oncreate of fragment
if (Build.VERSION.SDK_INT >= 23) {
checkPermissionForExternalStorage();
}
return myView;
}
#RequiresApi(api = Build.VERSION_CODES.M)
public boolean checkPermissionForExternalStorage(){
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
return true;
}
}
Override below method in fragment
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d("req_result", "success");
switch (requestCode) {
case EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Do your stuff here after user granted permissions
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
i have the following Custom Listener
package home.dan.signalstrengthatlocation;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CustomPhoneStateListener extends PhoneStateListener {
Context mContext;
public static String LOG_TAG = "CPhoneStateListener";
public CustomPhoneStateListener(Context context) {
mContext = context;
}
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
Log.i(LOG_TAG, "onSignalStrengthsChanged: " + signalStrength);
Intent i = new Intent("Signal_update");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("signals","signals updated");
CustomPhoneStateListener.this.mContext.startActivity(i);
//mContext.startActivity(i); also does not work
}
}
In the last command it tries to send data to the MainActivity Class to be picked up by it's onReceive method.
But this does not work. i get the following error.
android.content.ActivityNotFoundException: No Activity found to handle Intent
What is the best way to send data from above Listner class to the MainActivity class ?
EDIT -
Class below is supposed to receive information from above intent
package home.dan.signalstrengthatlocation;
import android.app.Activity;
import android.telephony.TelephonyManager;
import android.telephony.PhoneStateListener;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.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.TextView;
public class MainActivity extends AppCompatActivity {
private static final int NETWORKTYPE_WIFI = 0;
private static final int NETWORKTYPE_4G = 1;
private static final int NETWORKTYPE_2G = 2;
private static final int NETWORKTYPE_NONE = 3;
public TelephonyManager mTelephonyManager;
public PhoneStateListener mListener;
private Button start_btn,stop_btn;
private TextView textview;
private BroadcastReceiver broadcastReceiver;
private String coordinates;
public String getCoordinates() {
return coordinates;
}
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
private String signalStrength;
public String getSignalStrength() {
return signalStrength;
}
public void setSignalStrength(String signalStrength) {
this.signalStrength = signalStrength;
}
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setCoordinates(intent.getExtras().get("coordinates").toString());
updateScrollText();
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
private void updateScrollText(){
textview.append("\n"+getCoordinates()+" "+getSignalStrength());
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
GPS_Service gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
mTelephonyManager.listen(new CustomPhoneStateListener(this), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
start_btn = (Button) findViewById(R.id.button1);
stop_btn = (Button) findViewById(R.id.button2);
textview = (TextView) findViewById(R.id.textview);
if(!runtime_permissions()){
enable_buttons();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// TODO Extract the data returned from the child Activity.
setSignalStrength(data.getStringExtra("signals"));
updateScrollText();
}
}
private void enable_buttons(){
start_btn.setEnabled(true);
stop_btn.setEnabled(false);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
if(!stop_btn.isEnabled()){
start_btn.setEnabled(false);
stop_btn.setEnabled(true);
}
}
});
stop_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
if(!start_btn.isEnabled()){
start_btn.setEnabled(true);
stop_btn.setEnabled(false);
}
}
});
}
private boolean runtime_permissions(){
if(Build.VERSION.SDK_INT >= 23
&&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_PHONE_STATE},
100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
enable_buttons();
}else{
runtime_permissions();
}
}
}
}
In your onResume() of your MainActivity, add following
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("location_update");
intentFilter.addAction("signal_update);
registerReceiver(broadcastReceiver, intentFilter);
And then use sendBroadcast in CustomPhoneStateListener instead of startActivity.
Intent i = new Intent("signal_update");
i.putExtra("signals","signals updated");
CustomPhoneStateListener.this.mContext.sendBroadcast(i);
You'll receive both signal as well as location update here:
public void onReceive(Context context, Intent intent) {
if("signal_update".equals(intent.getAction())) {
//update UI for signal update
} else if ("location_update".equals(intent.getAction())) {
// update UI for location update
}
}
I am building a simple camera app that opens up the the system camera app on a button click and displays it in a image view.But the app is crashing on the startActivityForResult method.
MainActivity.java:
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
Button button;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
Bundle extra = data.getExtras();
Bitmap bitmap = (Bitmap) extra.get("data");
imageView.setImageBitmap(bitmap) ;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
button.setEnabled(true);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
});
}
}
log cat:
Process: com.eldhoittangeorge.camera11032017, PID: 587
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=org.cyanogenmod.snap/com.android.camera.PhotoCamera } from ProcessRecord{f228cdc 587:com.eldhoittangeorge.camera11032017/u0a132} (pid=587, uid=10132) with revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1684)
at android.os.Parcel.readException(Parcel.java:1637)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3093)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520)
at android.app.Activity.startActivityForResult(Activity.java:4225)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.eldhoittangeorge.camera11032017.MainActivity$1.onClick(MainActivity.java:42)
at android.view.View.performClick(View.java:5639)
at android.view.View$PerformClick.run(View.java:22391)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6088)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
call active take photo on button click
private void activeTakePhoto() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
} else {
takePicture();
}
}
public void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 22);
}
and override
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 110) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
takePicture();
}
}}
and manifest should have
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
why you are supposed to follow this procedure is because from marshmallow onward its mandatory to ask for self permission from the user before using camera and accessing galley irrespective of you have permission in your manifest.
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
Button button;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
Bundle extra = data.getExtras();
Bitmap bitmap = (Bitmap) extra.get("data");
imageView.setImageBitmap(bitmap) ;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA},110);
takingPhoto();
}
else {
takingPhoto();
}
}
public void takingPhoto(){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
});
}
}
Android Manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
MainActivity.java
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tv;
Button bn;
String imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tvimei);
bn = (Button)findViewById(R.id.button);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei = telephonyManager.getDeviceId();
bn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv.setText(imei);
}
});
}
}
I was trying to get imei number and display it on homepage for testing purpose but the app crashes as soon as I run it on the phone
Hi try to add permission if your device is marshmallow check the below code also
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
TextView tv;
Button bn;
String imei;
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tvimei);
bn = (Button)findViewById(R.id.button);
if(checkPermission()){
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei = telephonyManager.getDeviceId();
}else{
Snackbar.make(view,"Please give access to read your phone state.",Snackbar.LENGTH_LONG).show();
requestPermission();
}
bn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv.setText(imei);
}
});
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)){
Toast.makeText(getApplicationContext(),"Give permission to check whether internet is of or on.",Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view,"Permission Granted, Now you can check network status.",Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view,"Permission Denied, You cannot check networkstatus.",Snackbar.LENGTH_LONG).show();
}
break;
}
}
}