Android Manifest Permissions issues - java

I followed a tutorial online about how to create a simple app that can switch on and off your phone's cam-light.
<manifest....>
<uses-permission android:name = "android.permission.CAMERA"/>
<uses-feature android:name = "android.hardware.camera"/>
</manifest>
This is in android manifest.
The problem: it crashes when I press the ON button (made by me, in application)
Stack Trace:
07-17 22:27:13.990: E/AndroidRuntime(1775): FATAL EXCEPTION: main
07-17 22:27:13.990: E/AndroidRuntime(1775): java.lang.NullPointerException
07-17 22:27:13.990: E/AndroidRuntime(1775): at com.example.salpa.MainActivity$1.onClick(MainActivity.java:33)
07-17 22:27:13.990: E/AndroidRuntime(1775): at android.view.View.performClick(View.java:4204)
07-17 22:27:13.990: E/AndroidRuntime(1775): at android.view.View$PerformClick.run(View.java:17355)
07-17 22:27:13.990: E/AndroidRuntime(1775): at android.os.Handler.handleCallback(Handler.java:725)
Another strange thing: when I install the app, there are no details about what permissions is requiring.
"The application can acces the following on your phone:" and there's nothing. (despite the permissions in tutorial where it shows that the application needs permision to Camera.)
Can someone please help me, thanks.
setContentView(R.layout.activity_main);
Button aprinde =(Button)findViewById(R.id.aprinde);
//Button sting = (Button)findViewById(R.id.sting);
cameraObj = Camera.open();
aprinde.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view){
Camera.Parameters cameraParams = cameraObj.getParameters();
cameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cameraObj.setParameters(cameraParams);
cameraObj.startPreview();
}
} );

Your app is crashing because you are running it on an emulator, which doesn't have a back-facing camera.
The documentation for Camera#open():
Creates a new Camera object to access the first back-facing camera on the
device. If the device does not have a back-facing camera, this returns
null.
You can fix the crash by checking for null.
public void onClick(View v) {
if (cameraObj == null) {
return;
}
Camera.Parameters cameraParams = cameraObj.getParameters();
cameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cameraObj.setParameters(cameraParams);
cameraObj.startPreview();
}
You should also look out for setParameters as this could crash too if the device doesn't have a flash.
public void onClick(View v) {
if (cameraObj == null) {
return;
}
Camera.Parameters cameraParams = cameraObj.getParameters();
if (cameraParams.getFlashMode() == null) {
return;
}
cameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cameraObj.setParameters(cameraParams);
cameraObj.startPreview();
}

Related

I can't start torch in device with API <=22(Used Android Studio and Unity) .why?

Hi friends I'm trying to make torch application in unity.From documentation I have noticed that setTorchMode() is applicable only if we have API>22. It works fine for API>22.But for below API<23 I have followed this. But even though my application in not staring torch in API<23 . From Logcat I have traced that CameraService: Permission Denial: can't use the camera
Detail Error Report:
08-18 09:27:22.343 758-835/? I/ActivityManager: Killing
14121:com.google.android.partnersetup/u0a7 (adj 15): DHA:empty #19
08-18 09:27:22.343 196-2615/? W/ServiceManager: Permission failure:
android.permission.CAMERA from uid=10242 pid=14010
08-18 09:27:22.343 196-2615/? E/CameraService: Permission Denial: can't
use the camera pid=14010, uid=10242
08-18 09:27:22.343 14010-14051/? W/CameraBase: An error occurred while
connecting to camera: 0
08-18 09:27:22.353 14010-14051/? E/ContentValues: TorchMode:
java.lang.RuntimeException: Fail to connect to camera service
`enter code here`at android.hardware.Camera.<init>(Camera.java:568)
at android.hardware.Camera.open(Camera.java:426)
at
com.mugames.torchlibrary.AndroidTrochClass.TorchMode
(AndroidTrochClass.java:64)
at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
at com.unity3d.player.UnityPlayer.access$300(Unknown Source)
at com.unity3d.player.UnityPlayer$e$1.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:145)
at com.unity3d.player.UnityPlayer$e.run(Unknown Source)
Here is my C# (Unity Code)
private void Awake()
{
if(!Permission.HasUserAuthorizedPermission(Permission.Camera))
{
Permission.RequestUserPermission(Permission.Camera);
}
}
void Start()
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
javaObject = new AndroidJavaObject("com.mugames.torchlibrary.AndroidTrochClass");
javaObject.Call("Init", context);
javaObject.Call("TorchMode", true);
}
Also Here is my Java code(Name of JAVA class is AndroidTrochClass) for API<23
try {
if(camera== null && parameters==null) {
camera = Camera.open();
parameters = camera.getParameters();
List<String> modesAvailable = parameters.getSupportedFlashModes();
if (modesAvailable.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
} else if (modesAvailable.contains((Camera.Parameters.FLASH_MODE_ON))) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
} else {
Log.d("Unity", "No Flash Available");
}
camera.setParameters(parameters);
}
if (state) {
camera.startPreview();
} else {
camera.stopPreview();
}
}
catch (Exception e)
{
Log.e(TAG, "TorchMode: ",e);
e.printStackTrace();
}
NOTE: I'm using Java Class Just as Plugin So Java Class extend to nothing so I have passed current context to Java Methods
Found!! I need to add Camera permission in manifest file ;)

Sinch VideoCaptureThread problem with camera "1" on android 9

I'm making a small app, I use sinch for video calling and it works fine on android 8.1 and lower. But on android 9, my app crash when I make a video call. and this is the error:
2019-02-11 11:36:56.895 1638-2821/? E/AndroidRuntime: FATAL EXCEPTION: VideoCapturerThread
Process: com.example.myapp.app, PID: 1638
java.lang.SecurityException: validateClientPermissionsLocked:1054: Caller "com.example.myapp.app" (PID 10319, UID 1638) cannot open camera "1" without camera permission
at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:747)
at android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:405)
at android.hardware.camera2.CameraManager.openCameraForUid(CameraManager.java:567)
at android.hardware.camera2.CameraManager.openCamera(CameraManager.java:495)
at org.webrtc.Camera2Session.openCamera(Unknown Source:44)
at org.webrtc.Camera2Session.start(Unknown Source:60)
at org.webrtc.Camera2Session.<init>(Unknown Source:73)
at org.webrtc.Camera2Session.create(Unknown Source:17)
at org.webrtc.Camera2Capturer.createCameraSession(Unknown Source:17)
at org.webrtc.CameraCapturer$5.run(Unknown Source:52)
at android.os.Handler.handleCallback(Handler.java:891)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:207)
at android.os.HandlerThread.run(HandlerThread.java:65)`
Try this method for video capture with camera may be it helps you:-
public void dispatchTakeVideoIntent() {
PermissionUtil.with(this).setCallback(new PermissionUtil.PermissionGrantedListener() {
#Override
public void onPermissionResult(boolean isGranted, int requestCode) {
if (isGranted) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, AppConstants.REQUEST_CODE.REQUEST_VIDEO_CAPTURE);
}
}
}
}).validate(Manifest.permission.CAMERA);
}
for the permission Util check this link https://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/

App keep crashing when i try open camera javaclass

So i try to build the Flickr app.
In this i use a Bottom Navigation View Adapter to switch between 5 activity ( Camera, News, User, Search, Noti). In Camera activity i intent camera but it keep crash down.
Code are like this:
CameraActivity.java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera1);
Log.d(TAG, "onCreate: Started");
photo = (ImageView)findViewById(R.id.dcm);
button= (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = getFile();
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(camera,CAMERA_REQUEST);
}
});
}
private File getFile() {
File folder = new File("sdcard/camera_app");
if (!folder.exists()){
folder.mkdir();
}
File image_file = new File(folder,"cam_image.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String path = "sdcard/camera_app/cam_image.jpg";
photo.setImageDrawable(Drawable.createFromPath(path));
setupBottomNavigationView();}
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: Setting up bottom navigation view");
BottomNavigationViewEx bottomNavigationView = (BottomNavigationViewEx) findViewById(R.id.bottomNavView);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
BottomNavigationViewHelper.enableNavigation(CameraActivity.this, this, bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(ActivityNumber);
menuItem.setChecked(true);}
I have added camera activity in manifest too.
AndroidManifest.xml
<uses-feature android:name="android.hardware.camera2"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
This is my Logcat: ( I think error start form these):
11-26 14:39:29.480 4983-4983/usth.edu.vn.ictflickr E/AndroidRuntime: FATAL EXCEPTION: main
Process: usth.edu.vn.ictflickr, PID: 4983
android.os.FileUriExposedException: file:///sdcard/camera_app/cam_image.jpg exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1958)
at android.net.Uri.checkFileUriExposed(Uri.java:2348)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:941)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9735)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9720)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1609)
at android.app.Activity.startActivityForResult(Activity.java:4472)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4430)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:732)
at usth.edu.vn.ictflickr.Camera.CameraActivity$1.onClick(CameraActivity.java:55)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
11-26 14:39:29.481 1361-3102/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 1554635 , only wrote 1554480
11-26 14:39:29.484 1623-1634/system_process W/ActivityManager: Force finishing activity usth.edu.vn.ictflickr/.Camera.CameraActivity
11-26 14:39:29.490 1623-1641/system_process I/ActivityManager: Showing crash dialog for package usth.edu.vn.ictflickr u0
11-26 14:39:29.495 1623-1639/system_process E/memtrack: Couldn't load memtrack module
Problem 2: I would like to apply some filter on image captured then upload it to flickr? Anybody know how to do it? But after my app don't crash down when i open camera. Thanks

FATAL EXCEPTION: main on Android App

I'm getting this fatal exception: main error. It is only when I click on the 'Pick A Place' button on my app.
The logcat report when clicking on the 'Pick A Place' button is below:
04-13 13:52:19.418 10737-10737/cct.mad.lab E/AndroidRuntime: FATAL EXCEPTION: main
Process: cct.mad.lab, PID: 10737
java.lang.NoSuchMethodError: cct.mad.lab.SettingsActivity.checkSelfPermission
at cct.mad.lab.SettingsActivity.calculateCurrentCoordinates(SettingsActivity.java:679)
at cct.mad.lab.SettingsActivity.onPrepareDialog(SettingsActivity.java:581)
at android.app.Activity.onPrepareDialog(Activity.java:3061)
at android.app.Activity.showDialog(Activity.java:3124)
at android.app.Activity.showDialog(Activity.java:3075)
at cct.mad.lab.SettingsActivity$8.onClick(SettingsActivity.java:374)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The logcat points to a 'NoSuchMethodError' when checking for 'self permission' to do with the method 'calculateCurrentCooridnates'. This method is below:
#TargetApi(Build.VERSION_CODES.M)
private void calculateCurrentCoordinates() {
float lat = 0, lon = 0;
try {
LocationManager locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = (float) recentLoc.getLatitude();
lon = (float) recentLoc.getLongitude();
} catch (Exception e) {
Log.e(DEBUG_TAG, "Location failed", e);
}
mFavPlaceCoords = new GPSCoords(lat, lon);
}
The ToDo was automatically generated when Android Studio automatically added the '#TargetAPI' bit. With this in mind I added the following to the manifest and as I got no more errors I thought this would be enough:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, the app just crashes.
Any help greatly appreciated.
Thanks
Extending AppCompatActivity will solve the issue.
Do like this
public class SettingsActivity extends AppCompatActivity {

NullPointerException when use getLaunchIntentForPackage

I'm trying to start a third party app(here is Launcher) by using this code:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String currentHomePackage = resolveInfo.activityInfo.packageName;
openApp(getApplicationContext(),currentHomePackage);
openApp:
public static boolean openApp(Context context, String packageName) {
PackageManager manager = context.getPackageManager();
try {
Intent i = manager.getLaunchIntentForPackage(packageName);
if (i == null) {
return false;
//throw new PackageManager.NameNotFoundException();
}
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
return true;
} catch (Exception e) {
return false;
}
}
but I get a NullPointerException! This code gets my launcher package name correctly, but I can't open it! Help me please and don't get me negative points!
logcat:
07-30 18:59:47.206 16079-16079/ir.whiteapp.keepme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at ir.whiteapp.keepme.AlertBox.openApp(AlertBox.java:80)
at ir.whiteapp.keepme.AlertBox$1.onClick(AlertBox.java:52)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
There is no requirement that getLaunchIntentForPackage() return anything. Quoting the documentation:
Returns: A fully-qualified Intent that can be used to launch the main activity in the package. Returns null if the package does not contain such an activity, or if packageName is not recognized.
In particular, a home screen implementation does not need a launch Intent (ACTION_MAIN/CATEGORY_LAUNCHER), as normally it is not launched by other home screen implementations.

Categories