我想制作一个没有 UI 的应用程序,当按下应用程序的图标时,它将打开/关闭手电筒。
我试图制作一个部分工作的透明活动(当手电筒关闭时工作,但当打开并使用应用程序的图标将其关闭时,它会关闭但应用程序崩溃并显示错误对话框)。
我认为上述方法不是实现我想要的东西的好方法,并且可能需要使用服务,但我是开发新手,我真的不知道如何编写服务。
因此,我请您指导我使用应用程序的图标快捷方式打开/关闭切换手电筒的最佳方法是什么,并可能提供一个基本示例。提前致谢。
这是代码:
public class Flashlight extends Activity {
private boolean isLighOn = false;
private Camera camera;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
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;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
finish();
};
@Override
public void onPause() {
super.onPause();
bundle.putBoolean("toggleFlashlight", isLighOn);
}
public void onResume() {
super.onResume();
}
@Override
protected void onStop() {
super.onStop();
}
}
}
这是 logcat 错误:
E/QualcommCamera( 116): Qint android::get_camera_info(int, camera_info*): E
I/QualcommCameraHardware( 116): Found a matching camera info for ID 0
I/QualcommCameraHardware( 116): HAL_getCameraInfo: orientation = 90
I/QualcommCameraHardware( 116): HAL_getCameraInfo: modes supported = 5
W/CameraService( 116): CameraService::connect X (pid 6147) rejected (existing c
lient).
W/dalvikvm( 6147): threadid=1: thread exiting with uncaught exception (group=0x4
0c911f8)
E/AndroidRuntime( 6147): FATAL EXCEPTION: main
E/AndroidRuntime( 6147): java.lang.RuntimeException: Unable to start activity Co
mponentInfo{com.myprojects.lightsonoff/com.myprojects.lightsonoff.Flashlight}: j
ava.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime( 6147): at android.app.ActivityThread.performLaunchActiv.....