Here is all the code to run Falsh in the background. all you need to put your code in the service. then start your service with your core business.
Here is the class of service:
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; }
Remember to add this to your manifest:
<service android:name=".ServiceFlash" android:exported="false"/>
Your activity may be this: the public class AppActivity extends the action {private boolean isFlashOn = false; private camera; private button buttons;
@Override protected void onStop() { super.onStop(); if (camera != null) { camera.release(); } } @Override protected void onPause() {
}
You can start your service from a widget class like this (try putting this code inside the onReceive method of the widget class):
// Create intent Intent serviceIntent = new Intent(context, mService.class); // start service context.startService(serviceIntent);
Enjoy! ..
source share