Skip to content Skip to sidebar Skip to footer

Flashlight Turns Off When Other Apps Are Started. Android

I am working on Flashlight app with Widget. When I turn on Flashlight with Widget flashlight is on, and when I start some app, the flashlight turns off. Why is this happening? Why

Solution 1:

Here is the whole code to run Falsh in background. all you need to put your code in a service. then start your service from your main activity.

Here is the service class:

publicclassServiceFlashextendsService {
privatebooleanisFlashOn=false;
private Camera camera;
Context context ;
PackageManager pm;


@OverridepublicvoidonCreate() {
    // TODO Auto-generated method stub
    context = getApplicationContext();
    super.onCreate();

}
@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
     pm = context.getPackageManager();

    if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Log.e("err", "Device has no camera!");
        Toast.makeText(getApplicationContext(),
                "Your device doesn't have camera!", Toast.LENGTH_SHORT)
                .show();

        return0;
    }

    camera = Camera.open();
    finalParametersp= camera.getParameters();

    // turn flash onif (isFlashOn) {
        Log.i("info", "torch is turned off!");
        p.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(p);
        isFlashOn = false;
    } else {
        Log.i("info", "torch is turned on!");
        p.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(p);
        isFlashOn = true;
    }
    returnsuper.onStartCommand(intent, flags, startId);

}

@Overridepublic IBinder onBind(Intent intent) {
    // TODO Auto-generated method stubreturnnull;
}

Don't forget add this to your manifest:

<serviceandroid:name=".ServiceFlash"android:exported="false"/>

Your activity maybe like this: public class AppActivity extends Activity { private boolean isFlashOn = false; private Camera camera; private Button button;

@OverrideprotectedvoidonStop() {
    super.onStop();

    if (camera != null) {
        camera.release();
    }
}

@OverrideprotectedvoidonPause() {
    // TODO Auto-generated method stubsuper.onPause();

}

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Intent front_translucent = newIntent(this, ServiceFlash.class);

    startService(front_translucent);
}

}

You can start your service from widget class like this (try to put this code inside onReceive method of widget class):

// Create intent 
    Intent serviceIntent = newIntent(context, mService.class);
// start service 
context.startService(serviceIntent);

Enjoy..!

Post a Comment for "Flashlight Turns Off When Other Apps Are Started. Android"