dimanche 26 juin 2016

Implement stroboscope to flashlight app

i am kinda new to android and java programming, and i like it, i have made a flashlight app, and i want to add stroboscope to it, i saw some tutorials but i kinda messed it up, please be gentle to me :)), so here is my code and also i have with comented code which it did not worked,the one for stroboscope and it is not complete!

this is AndroidManifest.XML file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mihai_bucur.lanternuta">

<uses-permission android:name="android.permission.CAMERA"/>;
<uses-feature android:name="android.hardware.camera"/>;
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
 App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
</application>

and now this is MainActivity.java

package com.mihai_bucur.lanternuta;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.widget.SeekBar;


import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.security.Policy;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity {
ImageButton btnSwitch;

private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
int freq;
int sr;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //SeekBar

//        Activity rootView = null;
//        SeekBar skBar = (SeekBar) rootView.findViewById(R.id.seekBar);
//        skBar.setOnSeekBarChangeListener(new                   
 SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar skBar, int progress,         boolean fromUser) {
//                freq = progress;
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        });


    //butonul pentru aprindere flash
    btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

    /*
    //verificam intai daca are sau nu Bliț
    */

    hasFlash =    getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    if (!hasFlash) {
        //  dacă device-ul nu are blit
        // Arata un mesaj de eroare si inchide aplicatia
        AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
                .create();
        alert.setTitle("Eroare");
        alert.setMessage("Imi pare rău, device-ul tău nu are bliț!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // closing the application
                finish();
            }
        });
        alert.show();
        return;
    }
    btnSwitch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isFlashOn) {
                //opreset blit
                turnOffFlash();
            } else {
                //porneste blit
                turnOnFlash();
            }
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}


//    /**
//     * A placeholder fragment containing a simple view.
//     */  
//    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
//    public static class PlaceholderFragment extends Fragment {
//        private Camera cam;
//        private Camera.Parameters camParams;
//        private boolean hasCam;
//        private int freq;
//        private StroboRunner sr;
//        private Thread t;
//        private boolean isChecked = false;
//
//        public PlaceholderFragment() {
//        }

    // cauta parametrii camera

    @SuppressLint("LongLogTag")
    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {
                Log.e("Eroare Cameră.Nu s-a putut deschide. Error: ", e.getMessage());
            }
        }
    }
    /*
    Pornesc Blit-ul
     */


    private void turnOnFlash() {
        if (!isFlashOn) {
            if (camera == null || params == null & freq != 0) {
//                    sr = new StroboRunner();
//                    sr.freq = freq;
//                    t = new Thread(sr);
//                    t.start();
                return;
            }
            //sunet
            playSound();

            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;

            //schimba imaginea butonului
            toggleButtonImage();

        }
    }


    /*
     * Sunet
     * se va auzi cand se schimba de pe on pe off si invers
     * */
    private void playSound() {
        if (isFlashOn) {
            mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
        } else {
            mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
        }
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
            }
        });
        mp.start();
    }

    /*
    Opresc Blit-ul
     */
    private final void turnOffFlash() {
        if (isFlashOn) {
   //        if (camera == null || params == null & t != null) {
   //           sr.stopRunning = true;
   //           t = null;
                return;
            }
            // sunet
            playSound();

            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;

            // scimba imaginea butonului
            toggleButtonImage();
        }


    //ia imaginile si le schimba pentru fiecare state , on sau off
    private void toggleButtonImage() {
        if (isFlashOn) {
            btnSwitch.setImageResource(R.drawable.btn_switch_on);
        } else {
            btnSwitch.setImageResource(R.drawable.btn_switch_off);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

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

        // cand este in pauza aplicatie opreste blit
        turnOffFlash();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

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

        // la revenire porneste blitul
        if (hasFlash)
            turnOnFlash();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // ATTENTION: This was auto-generated to implement the App Indexing   API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();

        // la pornirea aplicatiei ia parametrii device-ului
        getCamera();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.mihai_bucur.lanternuta/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.mihai_bucur.lanternuta/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);

        // la oprire nu te mai folosi de camera
        if (camera != null) {
            camera.release();
            camera = null;
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.disconnect();
    }
}

I know i am a little newbie, but i want to learn, hope you can provide me an answer.

P.S:Before i tried to add strobe the app it worked, now it is crashing on emulator.

P.S 2: I am not planning to launch the app on store, it is just for me ,just for learning

Thanks!

Aucun commentaire:

Enregistrer un commentaire