Flashlight turns off when other apps are started. Android

女生的网名这么多〃 提交于 2019-12-01 22:53:19

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:

public class ServiceFlash extends Service {
private boolean isFlashOn = false;
private Camera camera;
Context context ;
PackageManager pm;


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

}
@Override
public int onStartCommand(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();

        return 0;
    }

    camera = Camera.open();
    final Parameters p = camera.getParameters();

    // turn flash on
    if (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;
    }
    return super.onStartCommand(intent, flags, startId);

}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

Don't forget add this to your manifest:

<service
        android: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;

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

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

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Intent front_translucent = new Intent(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 = new Intent(context, mService.class);
// start service 
context.startService(serviceIntent);

Enjoy..!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!