I am working on Flashlight app with Widget. When I turn on Flashlight with Widget flashlight is on, and when I start some app, the flashlight turns off. Why is this happening? W
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..!