Android Open Source - 101androidapps Main Activity

From Project

Back to project page 101androidapps.


The source code is released under:

MIT License

If you think the Android project 101androidapps listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.stevescodingblog.androidapps.flashlight;
//from   ww  w .jav a 2 s. c  o  m
import android.content.Context;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends Activity {

    static Camera _camera = null;   // static so that the instance remains across activity resets

    Useful stuff which helped to get this working:

    protected void onCreate(Bundle savedInstanceState) {

        final Context context = getApplicationContext();

        // Check that we have a camera flash
        boolean hasFlash = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        Button toggleButton = (Button)this.findViewById(;

        // If we don't, show a message and hide the button
            Toast.makeText(context, "Your device does not have a camera flash!", Toast.LENGTH_LONG).show();

        // Toggle the flash when clicked
        toggleButton.setOnClickListener(new View.OnClickListener(){

            public void onClick(View view) {
                try {

                    // If we haven't got an instance of the camera..
                    if(_camera == null) {

                        // Open it
                        _camera =;

                        // Some devices need a preview texture in order to show the flash
                        _camera.setPreviewTexture(new SurfaceTexture(0));

                        Camera.Parameters parameters = _camera.getParameters();

                        // If we support Torch mode, then turn it on
                        List<String> flashModes = parameters.getSupportedFlashModes();

                        if (flashModes.contains(Camera.Parameters.FLASH_MODE_TORCH)) {

                    else {
                        _camera = null;
                catch(Exception e) {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();

Java Source Code List