【问题标题】:Flash should turn on when double click power button双击电源按钮时闪光灯应打开
【发布时间】:2018-05-14 06:57:37
【问题描述】:

我有一个应用程序,其中只有一个切换按钮。这个切换按钮的功能是当我按下它时打开闪光灯,当我再次按下它时关闭闪光灯。但我希望即使我的设备被锁定、睡眠或工作时也能发生这种情况。每当我双击电源按钮时,应用程序功能应该在服务中运行,并通过广播它应该打开闪光灯。请让我知道如何做到这一点。

【问题讨论】:

    标签: android flash service broadcastreceiver


    【解决方案1】:

    MainActivity

    package com.example.salal_khan.flashlightservices;
    
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    
    public class MainActivity extends AppCompatActivity {
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
    
            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;
            }
            startService();
        }
    
    
        public void startService() {
            startService(new Intent(getBaseContext(), MyService.class));
        }
    
        // Method to stop the service
        public void stopService() {
            stopService(new Intent(getBaseContext(), MyService.class));
        }
    }
    

    服务

    package com.example.salal_khan.flashlightservices;
    
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.pm.PackageManager;
    import android.hardware.Camera;
    import android.os.Binder;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.util.Log;
    import android.widget.Toast;
    
    /**
     * Created by salal-khan on 12/1/2017.
     */
    public class MyService extends Service {
    
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Let it continue running until it is stopped.
            Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    
            final IntentFilter filter = new 
            IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_USER_PRESENT);
            final BroadcastReceiver mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    
    
    
        }
    
    
    
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
    
    }
    

    广播接收器

    package com.example.salal_khan.flashlightservices;
    
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.hardware.Camera;
    import android.util.Log;
    import android.hardware.Camera.Parameters;
    
    /**
     * Created by salal-khan on 12/1/2017.
     */
    
    public class ScreenReceiver extends BroadcastReceiver {
    
        public static boolean wasScreenOn = true;
    
    
        Camera camera;
        boolean isON = false;
    
        int number_of_clicks = 0;
        boolean thread_started = false;
        final int DELAY_BETWEEN_CLICKS_IN_MILLISECONDS = 550;
    
    
        @Override
        public void onReceive(final Context context, final Intent intent) {
            ++number_of_clicks;
            if (!thread_started) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        thread_started = true;
                        try {
                            Thread.sleep(DELAY_BETWEEN_CLICKS_IN_MILLISECONDS);
                            if (number_of_clicks == 1) {
    
                            } else if (number_of_clicks == 2) {
    
                                if (isON) {
    
                                    if (camera == null) {
                                        camera = Camera.open();
                                    }
    
                                    Parameters p = camera.getParameters();
                                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                                    camera.setParameters(p);
                                    camera.stopPreview();
                                    isON = false;
                                } else {
                                    if (camera == null) {
                                        camera = Camera.open();
                                    }
                                    Parameters p = camera.getParameters();
                                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                                    camera.setParameters(p);
                                    camera.startPreview();
                                    isON = true;
                                }
                            }
                            number_of_clicks = 0;
                            thread_started = false;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
    
                Log.e("LOB", "onReceive");
                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    wasScreenOn = false;
                }
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
                {
                    wasScreenOn = true;
                }
                else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                    Log.e("LOB", "userpresent");
                    Log.e("LOB", "wasScreenOn" + wasScreenOn);
                }
        }
    }
    

    清单

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.salal_khan.flashlightservices">
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" />
        <uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <service android:name=".MyService" />
        </application>
    
    </manifest>
    

    【讨论】:

      【解决方案2】:

      捕获图像

      package com.example.salal_khan.SecuriteCameraServices;
      
      import android.content.BroadcastReceiver;
      import android.content.ContentValues;
      import android.content.Context;
      import android.content.Intent;
      import android.graphics.PixelFormat;
      import android.hardware.Camera;
      import android.net.Uri;
      import android.os.Handler;
      import android.os.Looper;
      import android.provider.MediaStore;
      import android.util.Log;
      import android.hardware.Camera.Parameters;
      import android.view.SurfaceView;
      import android.widget.Toast;
      
      import java.io.FileNotFoundException;
      import java.io.IOException;
      import java.io.OutputStream;
      
      /**
       * Created by salal-khan on 12/1/2017.
       */
      
      public class ScreenReceiver extends BroadcastReceiver {
      
          public static boolean wasScreenOn = true;
      
      
          Camera camera = null;
          boolean isON = false;
      
          int number_of_clicks = 0;
          boolean thread_started = false;
          final int DELAY_BETWEEN_CLICKS_IN_MILLISECONDS = 550;
          Context contexts;
      
          @Override
          public void onReceive(final Context context, final Intent intent) {
              contexts = context;
              ++number_of_clicks;
              final SurfaceView mview = new SurfaceView(context);
              if (camera==null) {
                  camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
              }
              if (!thread_started) {
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          thread_started = true;
                          try {
                              Thread.sleep(DELAY_BETWEEN_CLICKS_IN_MILLISECONDS);
                              if (number_of_clicks == 1) {
      
                              } else if (number_of_clicks == 2) {
      
                                  if (isON) {
      
                                      Camera.Parameters parameters = camera.getParameters();
                                      parameters.setPictureFormat(PixelFormat.JPEG);
                                      camera.setParameters(parameters);
      
      
                                      Handler h = new Handler(Looper.getMainLooper());
                                      h.post(new Runnable() {
                                          public void run() {
      
                                              try {
                                                  camera.setPreviewDisplay(mview.getHolder());
                                                  camera.startPreview();
                                                  camera.takePicture(null, null, photoCallback);
      
                                              } catch (IOException e) {
                                                  // TODO Auto-generated catch block
                                                  e.printStackTrace();
                                              }
                                          }
                                      });
      
      
                                  } else {
      
      
                                      Camera.Parameters parameters = camera.getParameters();
                                      parameters.setPictureFormat(PixelFormat.JPEG);
                                      camera.setParameters(parameters);
      
      
                                      Handler h = new Handler(Looper.getMainLooper());
                                      h.post(new Runnable() {
                                          public void run() {
      
                                              try {
      
                                                  camera.setPreviewDisplay(mview.getHolder());
                                                  camera.startPreview();
                                                  camera.takePicture(null, null, photoCallback);
      
                                              } catch (IOException e) {
                                                  // TODO Auto-generated catch block
                                                  e.printStackTrace();
                                              }
                                          }
                                      });
                                  }
                              }
                              number_of_clicks = 0;
                              thread_started = false;
                          } catch (InterruptedException e) {
                              e.printStackTrace();
                          }
                      }
                  }).start();
      
      
                  Log.e("LOB", "onReceive");
                  if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                      wasScreenOn = false;
                  }
              } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                  wasScreenOn = true;
              } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                  Log.e("LOB", "userpresent");
                  Log.e("LOB", "wasScreenOn" + wasScreenOn);
              }
          }
      
      
          Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
              public void onPictureTaken(byte[] data, Camera camera) {
      
                  Uri uriTarget = contexts.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
                  OutputStream imageFileOS;
      
                  try {
      
                      imageFileOS = contexts.getContentResolver().openOutputStream(uriTarget);
                      imageFileOS.write(data);
                      imageFileOS.flush();
                      imageFileOS.close();
      
      //                Toast.makeText(contexts.getApplicationContext(), "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
      
                  } catch (FileNotFoundException e) {
                      e.printStackTrace();
      
                  } catch (IOException e) {
                      e.printStackTrace();
      
                  }
      
              }
          };
      }
      

      清单

      <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.salal_khan.SecuriteCameraServices">
          <uses-permission android:name="android.permission.CAMERA" />
          <uses-feature android:name="android.hardware.camera" />
          <uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
          <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
          <uses-permission android:name="android.permission.CAMERA" />
      
          <uses-feature android:name="android.hardware.camera.autofocus" />
      
          <uses-permission android:name="android.permission.CAMERA" />
      
          <application
              android:allowBackup="true"
              android:name=".MyApplication"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:roundIcon="@mipmap/ic_launcher_round"
              android:supportsRtl="true"
              android:theme="@style/AppTheme">
              <activity android:name="com.example.salal_khan.SecuriteCameraServices.MainActivity">
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
              <service android:name="com.example.salal_khan.SecuriteCameraServices.MyService" />
          </application>
      
      </manifest>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-20
        • 1970-01-01
        • 2013-02-27
        相关资源
        最近更新 更多