androidflashlight

Running an android flashlight in background


How can I keep the flashlight on in the background even when I switch to next activity or next application. Also my flashlight turns off automatically when I my screen locks and I want to keep my flash glowing even the screen locks.

This is my current code:

private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_savedform);


    toolbar= (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

    // First check if device is supporting flashlight or not
    hasFlash = getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    if (!hasFlash) {
        // device doesn't support flash
        // Show alert message and close the application
        AlertDialog alert = new AlertDialog.Builder(SavedForm.this)
                .create();
        alert.setTitle("Error");
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // closing the application
                finish();
            }
        });
        alert.show();
        return;
    }

    // get the camera
    getCamera();

    // displaying button image
    toggleButtonImage();


    // Switch button click event to toggle flash on/off
    btnSwitch.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isFlashOn) {
                // turn off flash
                turnOffFlash();
            } else {
                // turn on flash
                turnOnFlash();
            }
        }
    });
}

// Get the camera
private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Error. Failed to Open", e.getMessage());
        }
    }
}

// Turning On flash
private void turnOnFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }
        // play sound
        playSound();

        params = camera.getParameters();
        params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();
        isFlashOn = true;

        // changing button/switch image
        toggleButtonImage();
    }

}

// Turning Off flash
private void turnOffFlash() {
    if (isFlashOn) {
        if (camera == null || params == null) {
            return;
        }
        // play sound
        playSound();

        params = camera.getParameters();
        params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
        camera.stopPreview();
        isFlashOn = false;

        // changing button/switch image
        toggleButtonImage();
    }
}

// Playing sound
// will play button toggle sound on flash on / off
private void playSound(){
    if(isFlashOn){
        mp = MediaPlayer.create(SavedForm.this, R.raw.flashoff);
    }else{
        mp = MediaPlayer.create(SavedForm.this, R.raw.flashon);
    }
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            mp.release();
        }
    });
    mp.start();
}


private void toggleButtonImage(){
    if(isFlashOn){
        btnSwitch.setImageResource(R.drawable.button_on);
    }else{
        btnSwitch.setImageResource(R.drawable.button_off);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
protected void onPause() {
    super.onPause();

    // on pause turn off the flash
    turnOnFlash();
}

@Override
protected void onRestart() {
    super.onRestart();
}


@Override
protected void onResume() {
    super.onResume();

    // on resume turn on the flash
    if(hasFlash)
        turnOffFlash();
}

@Override
protected void onStart() {
    super.onStart();

    // on starting the app get the camera params
    getCamera();
}

@Override
protected void onStop() {
    super.onStop();

    // on stop release the camera
    if (camera != null) {
        camera.release();
        camera = null;
    }
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_savedform, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    if(id==android.R.id.home){
        NavUtils.navigateUpFromSameTask(this);
    }

    return super.onOptionsItemSelected(item);
}
}

Solution

  • The best way to do is by Running a Background service that handles the Flashlight.

    You need to put your FlashLight Start and Stop code inside the OnStart and onDestroy of the Service. That you need to do on your own

    1. First of all create a class named FlashLightService that extends the Service
     public class FlashLightService extends Service {  
                          
                         @Override  
                         public IBinder onBind(Intent intent) {  
                          return null;  
                         }  
                         @Override  
                         public void onCreate() {  
                          Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();  
                         
                         }  
                         @Override  
                         public void onStart(Intent intent, int startid) {  
                         
                         // Put Your Code To Start the FlashLight Over Here
                    
                         }  
                         @Override  
                         public void onDestroy() {  
                      
                           // Put Your Code To Stop the FlashLight Over Here
                    
                           }  
    
    
    1. Now from any Activity you can start and stop the Flashlight according to your need

    To start The FlashLight

    startService(new Intent(this, FlashLightService.class));
    

    To stop the FlashLight

    stopService(new Intent(this, FlashLightService.class));
    
    1. Do not forget to mention this in your AndroidManifest.xml

    Let me know if this works! :)