2

I want to make an app without UI, which will toggle the flashlight on/off when pressing the app's icon.

I've tried to make a transparent activity which partially works (works when flashlight is off, but when is on and use the app' s icon to turn it off, it turns off but the app crashes with an error dialog).

I'm thinking that the above is not a good way to achive what I want, and probably need to use a service, but I'm new in developing and I don't really know how to code a service.

So, I'm asking you to guide me on which is the best approach for making a toggle flashlight on/off using the app' s icon shortcut, and maybe to give a base example. Thanks in advance.

Here is the code:

public class Flashlight extends Activity {

private boolean isLighOn = false;
private Camera camera;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_flashlight);

    Context context = this;
    PackageManager pm = context.getPackageManager();

    // if device support camera?
    if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Log.e("err", "Device has no camera!");
        return;
    }

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

    if (isLighOn) {

        Log.i("info", "torch is turn off!");

        p.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(p);
        camera.stopPreview();
        isLighOn = false;

    } else {

        Log.i("info", "torch is turn on!");

        p.setFlashMode(Parameters.FLASH_MODE_TORCH);

        camera.setParameters(p);
        camera.startPreview();
        isLighOn = true;

    }
    finish();

          };

      @Override
      public void onPause() {
      super.onPause();
  bundle.putBoolean("toggleFlashlight", isLighOn);
     }

     public void onResume() {
 super.onResume();
     }

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

   }
  }  
 }

And here is the logcat error:

E/QualcommCamera(  116): Qint android::get_camera_info(int, camera_info*): E
I/QualcommCameraHardware(  116): Found a matching camera info for ID 0
I/QualcommCameraHardware(  116): HAL_getCameraInfo: orientation = 90
I/QualcommCameraHardware(  116): HAL_getCameraInfo: modes supported = 5
W/CameraService(  116): CameraService::connect X (pid 6147) rejected (existing c
lient).
W/dalvikvm( 6147): threadid=1: thread exiting with uncaught exception (group=0x4
0c911f8)
E/AndroidRuntime( 6147): FATAL EXCEPTION: main
E/AndroidRuntime( 6147): java.lang.RuntimeException: Unable to start activity Co
mponentInfo{com.myprojects.lightsonoff/com.myprojects.lightsonoff.Flashlight}: j
ava.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime( 6147):        at android.app.ActivityThread.performLaunchActiv.....
dancer_69
  • 331
  • 2
  • 6
  • 20
  • This is how I understand you question: If flashlight of. Press on app's icon -> Toggle flashlight on. If flashlight on. Press on app's icon -> toggle flashlight off. All should be done without UI. Is that correct? – Einar Sundgren Dec 09 '12 at 11:03
  • Make an service which will read Logcat of android and decipher which application is launched. Once this is done you can maintain a flag which will toggle when the activity is launched. You can find logcat reader code from http://stackoverflow.com/questions/3290936/android-detect-when-other-apps-are-launched. – curious Dec 09 '12 at 11:11
  • @curious then you could kill flies with a machine gun. I mean, sure, it will work, but it's a bit overkill of a solution, isn't it? – mah Dec 09 '12 at 11:14

2 Answers2

1

The easiest way to accomplish this is to create an activity whose onCreate() method does what you need done (read the state of the light and toggle it), and then calls finish(). There's nothing wrong with a very short lived activity that never presents a UI.

mah
  • 39,056
  • 9
  • 76
  • 93
  • 1
    I already did this, but as I said, craches when the flashlight is on(turns it off though) and also it bothers me that when runs it shows for a second just the wallpaper. I don't want to see any change on home screen when the shorcut pressed and the flashlight toggles. Of course maybe I do something wrong(I just set trunsclusive the activity on android.manifest). So if I can fix these issues without the need for a different approach I will post my code to see what is wrong. – dancer_69 Dec 09 '12 at 11:19
  • The crash is fixable. In addition to posting your code, post the error. As to the UI flashing, I'm not sure if this can be eliminated via an activity or not, but if it cannot then your solution will get much more complicated to eliminate it -- you would have to create a widget instead of an activity, which indirectly means the user would need to manually install it to the launch screen. Keep in mind that there are many (free) flashlights already on the market, before you invest too much time and effort into this ;) – mah Dec 09 '12 at 11:22
  • 1
    I don't want to use a widget(I already have one). I want to do it from a shortcut because I will be able to change its icon to match with homescreen's theme. And also trying to improve coding experience and knowledge through it. – dancer_69 Dec 09 '12 at 11:32
  • 1
    Remove the call to `setContentView()` from your `onCreate()` -- since you don't want to display a UI this is not necessary and may stop the UI flickering you're seeing. The crash appears to be a permission problem but I'm only guessing; your logcat paste doesn't have enough information -- provide more if you need help (but read it, it might explain the error clearly also). – mah Dec 09 '12 at 12:32
  • Your `onPause()` puts a boolean into a bundle but that seems strange. You aren't showing the scope or initialization of bundle and so it's potentially an error point, but I think it's unrelated to the current crash. It's possible (if bundle == null) that fixing your current crash could cause this to crash. – mah Dec 09 '12 at 12:32
  • You can use Widget for your use case. Refer this link http://stackoverflow.com/questions/7515309/widget-for-turning-on-off-camera-flashlight-in-android – curious Dec 09 '12 at 12:47
  • The error is about RuntimeException:Failed to connect to Camera Service. But exists another problem which I didn't realised. Even when the app turns flashlight on, after 10-20 seconds it turns itself off again, and from logcat I get a message about: Activity Flashlight died. – dancer_69 Dec 09 '12 at 14:07
0

I couldn't make it work with this approach, so I created a service in which I started flashlight as a service. Then from the transparent activity I created an if statement which will start the sercvice if not running by checking a blobal boolean flag(which is included in service class), or stop it if already run. The only problem now was that the system kill the flashlight service very easy, so I inclued the startForeground method like this:

Notification fakenote = new Notification( 0, null, System.currentTimeMillis() );
    fakenote.flags |= Notification.FLAG_NO_CLEAR;
    startForeground( 2, fakenote );

Also I put stopForeground(true) in onDestroy method. Now seems that works fine. Is there any way to prevent system completely from killing the service, so it can be killed only by the app, or this is the best can be done?

dancer_69
  • 331
  • 2
  • 6
  • 20