即使切换到下一个活动或下一个应用程序,我如何也可以在背景中保持手电筒开着。当屏幕锁定时,即使屏幕锁定,我也要保持闪光灯发光,手电筒也会自动关闭。

这是我当前的代码:

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);
}
}

最佳答案

最好的方法是通过运行处理手电筒的后台服务。

您需要将FlashLight的启动和停止代码放入服务的OnStart和onDestroy中。你需要自己做


首先创建一个名为FlashLightService的类,以扩展Service

公共类FlashLightService扩展了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

               }

现在,您可以根据需要从任何活动中启动和停止手电筒


启动手电筒

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


停止手电筒

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



别忘了在AndroidManifest.xml中提及这一点


            android:name =“。FlashLightService”
            android:enabled =“ true” />


让我知道这个是否奏效! :)

10-08 07:00