android - 在后台运行安卓手电筒

标签 android flashlight

即使我切换到下一个 Activity 或下一个应用程序,我怎样才能让手电筒在后台保持打开状态。此外,当我的屏幕锁定时,我的手电筒会自动关闭,我希望即使在屏幕锁定时也能保持闪光灯发光。

这是我当前的代码:

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

最佳答案

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

您需要将手电筒启动和停止代码放在服务的 OnStart 和 onDestroy 中。你需要自己做的

  1. 首先创建一个名为 FlashLightService 的类来扩展服务
 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. 现在您可以根据需要从任何 Activity 启动和停止手电筒

启动手电筒

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

关闭手电筒

stopService(new Intent(this, FlashLightService.class));
  1. 不要忘记在您的 AndroidManifest.xml 中提及这一点

让我知道这是否有效! :)

关于android - 在后台运行安卓手电筒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35644885/

相关文章:

android - 计算appwidget的高度

java - Android - Canvas 圆必须在第二秒左右向右进行圆周运动?

android - xperia Z5 上的 LED 手电筒

java - Android Studio : Flashlight crashes when turning off

android - 手电筒在某些设备上不工作

android - 为什么注册位置更新会触发联系人刷新?

应用程序的 JavaPos。加载的 JCL 注册表中不存在服务

android - 如果 Activity 正在运行则发送 LocalBroadcast 否则从后台服务发送通知

ios - 在 ARSession 期间打开手电筒

Android:屏幕关闭后保持摄像头 LED 亮起