实施频闪仪到手电筒应用程序

时间:2016-06-25 18:00:34

标签: java android

我对Android和java编程有点新,我喜欢它,我已经制作了一个手电筒应用程序,我想添加频闪仪,我看到了一些教程,但我有点搞砸了,请对我温柔:)),所以这里是我的代码,而且我还有一个没用的代码,一个用于频闪仪的代码,它不完整!

这是AndroidManifest.XML文件

<?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>

现在这是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);




    //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();
}




    // 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) {
                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) {
                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();
    }
}

我知道我是一个小新手,但我想学习,希望你能给我一个答案。

P.S:在我尝试添加频闪之前,它已经运行了,现在它在模拟器上崩溃了。

P.S 2:我不打算在商店推出应用程序,它只适合我,只是为了学习

谢谢!

0 个答案:

没有答案