Почему у меня не выполняется

407
17 июля 2017, 14:43

Здравствуйте, скажите пожалуйста почему у меня не срабатывает событие surfaceChanged?

Главный Activity :

package com.example.lol.timeshot;
import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.DragEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    static final Integer CAMERA = 0x1;
    static final Integer WRITE_EXST = 0x2;
    static final Integer READ_EXST = 0x3;
    private ImageView image_view;
    SurfaceView camView; // drawing camera preview using this variable
    static SurfaceHolder surfaceHolder; // variable to hold surface for surfaceView which means display
    boolean camCondition = false;  // conditional variable for camera preview checking and set to false
    Button cap;    // image capturing button
    int height;
    int width;
    int rotate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display display = getWindowManager().getDefaultDisplay();
        width = display.getWidth();  // deprecated
        height = display.getHeight();  // deprecated
        getWindow().setFormat(PixelFormat.UNKNOWN);

        camView = (SurfaceView) findViewById(R.id.camerapreview);
        askForPermission(Manifest.permission.CAMERA,CAMERA);
        askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,WRITE_EXST);
        askForPermission(Manifest.permission.READ_EXTERNAL_STORAGE,READ_EXST);
        //STEP #1: Get rotation degrees
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
        int rotation = this.getWindowManager().getDefaultDisplay().getRotation();
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break; //Natural orientation
            case Surface.ROTATION_90: degrees = 90; break; //Landscape left
            case Surface.ROTATION_180: degrees = 180; break;//Upside down
            case Surface.ROTATION_270: degrees = 270; break;//Landscape right
        }
        rotate = (info.orientation - degrees + 360) % 360;
        // getWindow() to get window and set it's pixel format which is UNKNOWN
        getWindow().setFormat(PixelFormat.UNKNOWN);
        // refering the id of surfaceView
        camView = (SurfaceView) findViewById(R.id.camerapreview);
        // refering button id
        cap = (Button) findViewById(R.id.button2);
        // click event on button
        //startService(new Intent(this, ShotService.class));
        cap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mServer.shot(180);
            }
        });
    }
    boolean mBounded;
    ShotService mServer;
    @Override
    protected void onStart() {
        super.onStart();
        Intent mIntent = new Intent(this, ShotService.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);
    };
    ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(MainActivity.this, "Service is disconnected", Toast.LENGTH_SHORT).show();
            mBounded = false;
            mServer = null;
        }
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(MainActivity.this, "Service is connected", Toast.LENGTH_SHORT).show();
            mBounded = true;
            ShotService.LocalBinder mLocalBinder = (ShotService.LocalBinder)service;
            mServer = mLocalBinder.getServerInstance();
            mServer.startcam();
            surfaceHolder = camView.getHolder();
            // adding call back to this context means MainActivity
            surfaceHolder.addCallback(MainActivity.this);
            // to set surface type
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);

        }
    };
    @Override
    protected void onStop() {
        super.onStop();
        if(mBounded) {
            unbindService(mConnection);
            mBounded = false;
        }
    };
    public void onClickStop() {
        stopService(new Intent(this, ShotService.class));
    }

    private void askForPermission(String permission, Integer requestCode) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
                //This is called if user has denied the permission before
                //In this case I am just asking the permission again
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            }
        } else {
            // Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
            // getting access to the surface of surfaceView and return it to surfaceHolder

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "LOL", Toast.LENGTH_SHORT).show();
        }
    }

    int value;
    int degrees = 0;
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        value = this.getResources().getConfiguration().orientation;
        if (value == Configuration.ORIENTATION_PORTRAIT) {
            //orientation = "Portrait";
            mServer.camera.setDisplayOrientation(90);   // setting camera preview orientation
        }
        if (value == Configuration.ORIENTATION_LANDSCAPE) {
            mServer.camera.setDisplayOrientation(0);   // setting camera preview orientation
            //orientation = "Landscape";
        }
    }
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        Toast.makeText(this, "OKEY", Toast.LENGTH_LONG).show();
        // condition to check whether your device have camera or not
        //if (mServer.camera != null){
            try {
                mServer.camera.setPreviewDisplay(MainActivity.surfaceHolder); // setting preview of camera
                mServer.camera.startPreview();  // starting camera preview
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
       // }
    }
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        // TODO Auto-generated method stub
        mServer.stoppreviewcam();
    }
}

Мой Service (который по задумке должен работать, даже при закрытом приложении) :

package com.example.lol.timeshot;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ShotService extends Service {
    final String LOG_TAG = "myLogs";
    Camera camera; // camera class variable

    IBinder mBinder = new LocalBinder();
    public class LocalBinder extends Binder {
        public ShotService getServerInstance() {
            return ShotService.this;
        }
    }
    public void onCreate() {
        super.onCreate();
        Log.d(LOG_TAG, "onCreate");
    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    public void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "onDestroy");
    }
    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "onBind");
        return mBinder;
    }
    public void shot(int rotate) {
        //STEP #2: Set the 'rotation' parameter
        Camera.Parameters params = camera.getParameters();
        params.setRotation(rotate);
        camera.setParameters(params);
        // calling a method of camera class takepicture by passing one picture callback interface parameter
        camera.takePicture(null, null, null, mPictureCallback);
    }
    public void stoppreviewcam() {
        camera.stopPreview(); // stop preview using stopPreview() method
    }
    public void stopcam(){
        camera.release();       // releasing camera
        camera = null;          // setting camera to null when left
    }
    public void startcam(){
        camera = Camera.open();   // opening camera
    }

    Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        public void onPictureTaken(byte[] data, Camera c) {
            FileOutputStream outStream = null;
            try {
                // Directory and name of the photo. We put system time
                // as a postfix, so all photos will have a unique file name.
                outStream = new FileOutputStream("/sdcard/new_" + System.currentTimeMillis()+".jpg");
                outStream.write(data);
                outStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }
    };

    public void Focus() {
        camera.autoFocus(null);
    }
}
READ ALSO
Как задать классу имя отправителя? [Java]

Как задать классу имя отправителя? [Java]

У меня есть таймер TimerRepИ для каждого пользователя мне нужно после определенного кода создавать новый таймер с именем этого пользователя

408
ImageIO.read(URL input) не считывает картинку

ImageIO.read(URL input) не считывает картинку

В данный момент пишу утилиту, которая должна, помимо прочего, выгружать на жесткий диск картинки с сайтаДля работы с картинками использую...

327
Как можно выделить текст в Selenium?

Как можно выделить текст в Selenium?

Добрый день, подскажите как можно с помощью команд Selenium выделить слово на странице (как выделяем мышкой при копирование) и перейти к следующему...

468