Here Is my Code:
I have Added a github Permission code But it still Crashes
I have done every thing but it crashes Every Time
I also have added Permission for Camera in my manifest
parameter = camera.getParameters();
}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("App needs permission to access camera")
.setPositiveButton("Granted", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(myAppSettings);
}
}).setNegativeButton("Denied", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}
#Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token)
{[enter image description here][1]
token.continuePermissionRequest();
}
}).check();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
textview = (TextView) findViewById(R.id.textView);
flashLight = (ImageButton) findViewById(R.id.flash_light);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//askPermission(CAMERA,camera1);
flashLight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isFlashLightOn) {
turnOnTheFlash();
} else {
turnOffTheFlash();
}
}
});
logCat:
09-30 18:59:31.698 11339-11339/inducesmile.com.androidflashlightapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: inducesmile.com.androidflashlightapp, PID: 11339
java.lang.RuntimeException: Unable to resume activity {inducesmile.com.androidflashlightapp/inducesmile.com.androidflashlightapp.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3506)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.(Camera.java:647)
at android.hardware.Camera.open(Camera.java:510)
at inducesmile.com.androidflashlightapp.MainActivity.turnOffTheFlash(MainActivity.java:105)
at inducesmile.com.androidflashlightapp.MainActivity.onResume(MainActivity.java:165)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6791)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3477)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
09-30 18:59:31.804 11339-11347/inducesmile.com.androidflashlightapp I/art: Enter while loop.
I also had created a flashlight sensor based app a few months back. I have created gist for the code of the flashlight activity (both java and xml) and it seems to be working fine. Take a look at the below links and see if it helps:
https://gist.github.com/robillo/b27d37be3262164ee7f5532230c28c5a
https://gist.github.com/robillo/71afef65923138ed9d6011e3bd216249
Also, try doing your processing part of the activity in the if block in onCreate() like:
askForPermissions();
if(checkForPermission()){
//Do your processing here
}
The functions are:
void askForPermissions(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
}
boolean checkForPermission(){
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
It's tough to tell without seeing your turnOnTheFlash and turnOffTheFlash functions, but I'd guess that you are not properly releasing the camera at some point as shown by the documentation.
Related
Good Day, So I have this program where the user will scan a QR code and get the value of it in the SQLite database but before I get the value the dialog box pops-up messaging me that "there is no participant found". Below is my code:
This is my onStart override.
#Override
protected void onStart()
{
super.onStart();
getparticipantid = tvParticipantID.getText().toString();
etparticipantidvalue.setText(getparticipantid);
getParticipantIbeam();
}
This is my activity where it will load the data from the database once the user scans the QR code.
private void getParticipantIbeam()
{
SQLiteFunctionUlitity.GameIBeamParticipant memberInfo = SQLiteFunctionUlitity.getparticipantIbeam(getparticipantid, mDbHelper.getSqliteObjectWithReadable());
if (memberInfo != null)
{
tvParticipantName.setText(memberInfo.getParticipantName());
tvParticipantNation.setText(memberInfo.getParticipant_nationality());
tvParticipantCategory.setText(memberInfo.getCategory());
tvWave.setText(memberInfo.getWave_number());
tvCategory.setText(memberInfo.getCategory());
}
else
{
Context context = this;
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("No Participant found in the Game.");
builder1.setCancelable(true);
builder1.setPositiveButton("Scan Again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(GameiBeamLineTracing.this, ScanGameIbeam.class);
startActivity(intent);
finish();
}
});
builder1.setNegativeButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
onStop();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
As you can see I call the getParticipantIbeam activity in onStart method but when I call it, it reads the else statement rather than the if statement.
I know this is a simple if else statement and lifecycle but I am desperate to know the answer.
I have used the library for scanning QR code, its very simple it may help you.
QR Code implementation library for android, Click here (blikoon)
Definitely this library will solve your all QR Code related issue and dont forget to implement run time permissions like photo , gallery etc.
I am following the example of Pokemon Go app to show a window message likes
You need to [Location, Camera,...] access to use this application. Please allow access in this application [Setting]. Click [Cancel] to exit from this application
When I click the Setting, the application will go to Setting window of this application and I can accept all Permissions.
The Setting window can access by using the code
public void gotoSetting(){
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + getApplicationContext().getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
There are my permisions which are stored in a String array
String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA}
I used this code to check if all permission are checked, otherwise it returns false
public static boolean hasAllPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
However, I got an issue that event I did not check all permissions, but the application did not go to Setting again. In additions, I can show an window message to notify if the user did not check all permission. Finally, This is my code
private AlertDialog buildNotificationServiceAlertDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Pemissions Setting");
alertDialogBuilder.setMessage("You need to [Location, Camera,...] access to use this application. Please allow access in this application [Setting]. Click [Cancel] to exit from this application");
alertDialogBuilder.setPositiveButton("Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
gotoSetting();
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// If you choose to not enable the notification listener
// the app. will not work as expected
}
});
return(alertDialogBuilder.create());
}
In onCreate I have
private AlertDialog enableNotificationListenerAlertDialog;
if(!hasAllPermissions(this, PERMISSIONS)){
enableNotificationListenerAlertDialog = buildNotificationServiceAlertDialog();
enableNotificationListenerAlertDialog.show();
}
Update: Solved:. I was missing to call the hasAllPermissions in the onResume() function. Finally, my solution is
#Override
protected void onResume() {
super.onResume();
if(hasAllPermissions(this, PERMISSIONS)==false){
enableNotificationListenerAlertDialog = buildNotificationServiceAlertDialog();
enableNotificationListenerAlertDialog.show();
}
}
I read your question carefully and i notice one mistake in your first line of code.As your code start with "public voide gotoSetting()",The mistake is in the keyword spelling.By correcting, it can be written as "public void gotoSetting()".
I hope this will help you.
i am using glide to view images which am getting as url from database in my activity,and i am deleting an image in activity where after deleting next activity will be opened but first time the image is deleting without any error,second time if open to and press delete I am getting this error:
java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
This is my code to delete the image:
alert.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialogInterface, final int i) {
try {
final Query postRef = ref.child("Pendingevents").orderByChild("Eventtitle").equalTo(Title);
postRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().removeValue();
Toast.makeText(getApplicationContext(), "Event Deleted", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getApplicationContext(),PendingEvents.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
}
});
}catch (Exception e)
{
Toast.makeText(ApproveEvents.this, "Unknown Error,please Try Again", Toast.LENGTH_SHORT).show();
}
}
});
AlertDialog build=alert.create();
build.show();
}
});
Logcat:
java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
at com.a.a.e.o.b(Unknown Source)
at com.a.a.e.o.a(Unknown Source)
at com.a.a.f.a(Unknown Source)
at bootcamplearning.humanplanet.u.a(Unknown Source)
at com.google.android.gms.b.ol.a(Unknown Source)
at com.google.android.gms.b.qh.b(Unknown Source)
at com.google.android.gms.b.qn.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Update
It is better not to use the approach, described at the bottom of post.
The main idea is that Glide is concerned about lifecycle of an element where it works. If a Fragment or an Activity will be destroyed, Glide finishes its work for image processing. Here is a detailed discussion of the issue.
To sum up, you should check if your activity is alive before calling load going back from some AsyncTask or other threads:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && someActivity.isDestroyed()) {
return;
} else {
Glide.with(someActivity)
.load(imageUrl)
....;
}
Workaround, not recommended because it will lead to some unnecessary processing if Activity was destroyed. But it is easy to use and makes its work.
In Glide.with(context) try to pass Application context instead of Activity. In this case you should not depend from Activity lifecycle.
For example, in activity you could use this:
Glide.with(getApplicationContext())
.load(imageUrl)
.into(yourImageView);
Or in framgent:
Glide.with(getActivity().getApplicationContext())
.load(imageUrl)
.into(yourImageView);
In the fragment, use:
if(getActivity !=null) {
Glide.with(getActivity())
.load(imageUrl)
.into(yourImageView);
}
I am making an application that contains a part of activities that can be executed on pre marshmallow devices and some part of activities on marshmallow and above.
So what I want to do is don't let the application crash on pre marshmallow device that runs the activity that is supported on marshmallow device and just show a toast that your device does not support this module to access.
Here I am stuck on finger print module that crashes the applications on pre marshmallow device.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//do something
}
else
showToastMessage();
Error
FATAL EXCEPTION: main
java.lang.VerifyError: com/example/android/fingerprintdialog/MainActivity
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
In my application I have a download button that requires runtime permission.
This is how I managed to do it:
public static int MY_PERMISSIONS_REQUEST_DOWNLOAD_IMAGE = 1;
btnDownLoad.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
urlFromDownload();
}
});
public void urlFromDownload() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_DOWNLOAD_IMAGE);
} else {
DowloadFileFromUrl downloadwall = new DowloadFileFromUrl();
if (downloadwall.getStatus() == AsyncTask.Status.RUNNING) {
// My AsyncTask has not started yet
Toast.makeText(getActivity(), "Please wait until download is complete", Toast.LENGTH_SHORT).show();
} else {
downloadwall.execute(imageUrl);
}
}
} else {
DowloadFileFromUrl downloadwall = new DowloadFileFromUrl();
if (downloadwall.getStatus() == AsyncTask.Status.RUNNING) {
// My AsyncTask has not started yet
Toast.makeText(getActivity(), "Please wait until download is complete", Toast.LENGTH_SHORT).show();
} else {
downloadwall.execute(imageUrl);
}
}
}
I hope you understand my code. What I've done is wrote my download code twice. First for marshmallow and second for lower versions.
Just check whether installed app is using marshmallow or above Android OS.
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
{
// FingerPrint is supported by Android
// Show the FingerPrint touch screen.
}
else
{
//FingerPrint is not supported by Android
//Don't show the FingerPrint touch screen.
}
Put that within the below condition
if (Build.VERSION.SDK_INT >= 23) {
// Your code for
} else {
// Code for previous versions
}
I am using Opencv on my application and it works fine with Android 4.3 but it doesn't even open with Android 6.0.
I looked up for a solution on SO, and found one that says to set the package name. So I did it.
Follow code:
public static boolean initOpenCV(String Version, final Context AppContext,
final LoaderCallbackInterface Callback)
{
AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext, Callback);
Intent intent = new Intent("org.opencv.engine.BIND");
intent.setPackage("org.opencv.engine");
if (AppContext.bindService(intent,
helper.mServiceConnection, Context.BIND_AUTO_CREATE))
{
return true;
}
else
{
AppContext.unbindService(helper.mServiceConnection);
InstallService(AppContext, Callback);
return false;
}
}
But now I am getting the following error:
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.app.Dialog.show(Dialog.java:319)
in the following code:
case InstallCallbackInterface.NEW_INSTALLATION:
{
Looper.prepare();
Log.d("Debug", ""+mAppContext);
AlertDialog InstallMessage = new AlertDialog.Builder(mAppContext).create();
InstallMessage.setTitle("Package not found");
InstallMessage.setMessage(callback.getPackageName() + " package was not found! Try to install it?");
InstallMessage.setCancelable(false); // This blocks the 'BACK' button
InstallMessage.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
callback.install();
}
});
InstallMessage.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
callback.cancel();
}
});
InstallMessage.show();
} break;
I have searched and found some people saying to keep track of the main Context, because Threads doesn't have context. But my app already does this and use the main context to create the AlertDialogs and it still doesn't work.
The error is when the app show the AlertDialog.
I really don't know what else to do. Can someone help?
As far as I know in service or Aplication class you cant get context with View for android 6.0, so when OpenCv tries to show AlertDialog it does not know to what activity bind dialog and crashes.
Try to init OpenCv in Activity onCreate method before usage.
My working init method in MainActivity (code on kotlin):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, object : BaseLoaderCallback(this#HistoryActivity) {
override fun onManagerConnected(status: Int) {
if (LoaderCallbackInterface.SUCCESS == status)
Log.i(TAG, "OpenCV was loaded")
else
super.onManagerConnected(status)
}
})
}