【问题标题】:Running an android flashlight in background在后台运行安卓手电筒
【发布时间】:2016-06-09 06:22:01
【问题描述】:

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

这是我当前的代码:

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

【问题讨论】:

  • 您在 OnStop 中释放相机。这就是锁屏时闪光灯熄灭的原因
  • @Nick Isaacs 我删除了 camera.release();来自 OnStop() 的声明;方法。我遇到了另外两个问题。首先,当我打开锁屏时闪光灯关闭,下一个是打开闪光灯并按下工具栏上的后退按钮时闪光灯自动打开
  • 您的 OnPause 事件有一个 turnFlashLightOn() 调用。这就是为什么当你按下它时它会打开。您的 OnResume 检查手电筒是否打开,然后将其关闭,这就是为什么当您解锁时它会关闭
  • @NickIsaacs 我真的很困惑 onpause(); 时该做什么;和 onResume();我只想在单击打开按钮时打开闪光灯并保持发光,直到我按下按钮或关闭应用程序。请帮助
  • 您的 OnPause 调用 turnOnFlash()。这意味着当您离开活动时,闪光灯会打开。所以从 OnPause 中删除代码。您的 OnResume 调用 turnOffFlash。将此代码放在您的 OnDestroy() 中。在 OnResume 和 OnPause 中什么都不做

标签: android flashlight


【解决方案1】:

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

您需要将 FlashLight 启动和停止代码放在服务的 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. 现在,您可以从任何活动中根据需要启动和停止手电筒

启动手电筒

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

停止手电筒

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

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

【讨论】:

  • Vivek 兄弟,我还没有尝试过服务,所以我遇到了太多错误。如果您通过示例帮助我,我将不胜感激。谢谢您的帮助
  • 好的,伙计!这将是一种乐趣
【解决方案2】:

删除这些代码或行。

  `
    @Override
         protected void onStop() {
            super.onStop();
        // on stop release the camera`enter code here`
        if (camera != null) {
            camera.release();
            camera = null;
        }
`

它对我有用。

【讨论】:

    【解决方案3】:

    我不是安卓专家,但我会推荐,
    将其作为服务运行或作为单例线程运行。

    【讨论】:

      【解决方案4】:

      闪光灯取决于相机。您的onStop 方法包含:camera.release(),它将释放相机硬件,覆盖已实现的任何其他采集方法。

      您可以使用后台服务来控制相机硬件。从 Activity 启动它,并在您的应用关闭时停止服务。

      【讨论】:

        猜你喜欢
        • 2011-09-12
        • 1970-01-01
        • 2021-05-05
        • 1970-01-01
        • 1970-01-01
        • 2013-06-14
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        相关资源
        最近更新 更多