检测闪光灯是不是已经打开
Posted
技术标签:
【中文标题】检测闪光灯是不是已经打开【英文标题】:Detect if flash light is already turned on检测闪光灯是否已经打开 【发布时间】:2021-01-28 13:00:30 【问题描述】:我有一个带有简单切换开关的应用程序,可以打开和关闭手电筒,我需要可以用来检查手电筒是否已打开然后使用它来更改开关的切换状态的代码... 如果服务报告手电筒开启,我将发送广播意图将其关闭,反之亦然...我的应用程序逻辑在这里
class SecondActivity : AppCompatActivity
protected override void OnCreate(Bundle onSavedInstanceState)
//Switch definition
Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
//Setting the intial status of the switch to be unchecked by default
switch1.Checked=false;
//Adding delegate method to handle switch checked event
switch1.CheckedChange += delegate (object sender, CompoundButton.CheckedChangeEventArgs e)
if (e.IsChecked==true)
//Switch is on so turn on Flahlight
Flashlight.TurnOnAsync();
Toast.MakeText(Application.Context, "Switch is ON", ToastLength.Long).Show();
else
//Switch is unchecked so turn off flashlight
Flashlight.TurnOffAsync();
Toast.MakeText(Application.Context, "Switch is OFF", ToastLength.Long).Show();
;
//Code to check if flashlight was turned on by an extra app activity
用户可以在应用程序外打开手电筒,所以我只需要该代码来检查它是否已经打开,然后我将实施广播意图以适当地更改我的开关,感谢您的时间和贡献
【问题讨论】:
手电筒似乎只支持TurnOnAsync
和TurnOffAsync
。因此,假设您只想使用此 API,例如,我会在开始时通过将其关闭而不考虑其当前状态来将灯带入定义的状态。
这在我更新的答案中有效吗?***.com/questions/64341648/…
好吧,一开始听起来是个很酷的主意,但对我来说太不幸了。如果我现在去 Playstore 并安装蓝牙应用程序,不知何故,如果 AI 从外部触发器启用蓝牙,这些应用程序将知道并对 UI 进行必要的更改.. 蓝牙是否有该服务来检查其状态?
@Fildor,好的,只需要弄清楚
@Fildor,感谢您正在进行下载
【参考方案1】:
用户可以在应用程序外打开手电筒,所以我只需要该代码来检查它是否已经打开,然后我将实现广播意图以适当地更改我的开关,
你想达到如下gif的效果吗?
我写了两个应用来实现:
MyForegroundServiceDemo:使用Broadcast来管理flashlight
是否启用,以保持broadcastReceiver始终在后台或前台运行,我使用forground服务来实现它。然后在前台服务中注册广播接收器。
XandroidBroadcastRece:只需打开/关闭手电筒。
这是我的 MyForegroundServiceDemo 代码。
首先,您需要在AndroidManifest.xml
中添加相机和手电筒权限。
然后,这是我的 layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_
android:layout_>
<TextView
android:layout_
android:layout_
android:textSize="20dp"
android:text="Please see following switch"/>
<Switch
android:layout_
android:layout_
android:id="@+id/switch1"/>
<Button
android:layout_
android:layout_
android:id="@+id/button1"
android:text="start"/>
<Button
android:layout_
android:layout_
android:id="@+id/button2"
android:text="Stop"/>
<EditText
android:layout_
android:layout_
android:text="123@456"/>
</LinearLayout>
这是我的MainActivity.cs
。我使用Button1
启用前台服务。并暴露Switch
,我们可以在broadcastReceiver中控制它。
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
public static MainActivity Instance;
public static Switch switch1;
protected override void OnCreate(Bundle savedInstanceState)
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
Instance = this;
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button button1 = FindViewById<Button>(Resource.Id.button1);
Button button2 = FindViewById<Button>(Resource.Id.button2);
switch1 = FindViewById<Switch>(Resource.Id.switch1);
button2.Click += Button2_Click;
button1.Click += Button1_Click;
Intent intent;
private void Button2_Click(object sender, System.EventArgs e)
// throw new System.NotImplementedException();
Android.App.Application.Context.StopService(intent);
private void Button1_Click(object sender, System.EventArgs e)
intent = new Intent(Android.App.Application.Context, typeof(MyForegroundService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
StartForegroundService(intent);
// Android.App.Application.Context.StartForegroundService(intent);
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
这是关于MyForegroundService.cs
的代码。当我们在MyReceiver(BroadcastReceiver)
中接收到广播时,我们用MyTorchRegister
监控手电筒的状态
using Android.Hardware.Camera2;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Essentials;
namespace ForegroundServiceDemo
[Service]
class MyForegroundService : Service
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
CreateNotificationChannel();
string messageBody = "service starting";
Clipboard.ClipboardContentChanged += Clipboard_ClipboardContentChanged;
// / Create an Intent for the activity you want to start
Intent resultIntent = new Intent(this,typeof(Activity1));
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddNextIntentWithParentStack(resultIntent);
// Get the PendingIntent containing the entire back stack
PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
var notification = new Notification.Builder(this, "10111")
.SetContentIntent(resultPendingIntent)
.SetContentTitle("Foreground")
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
MyReceiver receiver = new MyReceiver();
RegisterReceiver(receiver, new IntentFilter("com.Java_Tutorial.CUSTOM_INTENT"));
return StartCommandResult.Sticky;
private async void Clipboard_ClipboardContentChanged(object sender, EventArgs e)
//throw new NotImplementedException();
var text = await Clipboard.GetTextAsync();
Toast.MakeText(this, text, ToastLength.Long).Show();
if (text.Contains("@"))
await Clipboard.SetTextAsync(text.Replace("@", ""));
public override void OnDestroy()
base.OnDestroy();
Clipboard.ClipboardContentChanged -= Clipboard_ClipboardContentChanged;
StopForeground(true);
public override IBinder OnBind(Intent intent)
return null;
void CreateNotificationChannel()
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
return;
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
Description = channelDescription
;
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
//do you work
[BroadcastReceiver(Enabled = true, Exported = true)]
public class MyReceiver : BroadcastReceiver
public override void OnReceive(Context context, Intent intent)
CameraManager cameraManager = (CameraManager)context.GetSystemService(Context.CameraService);
var flashAvailable = cameraManager.GetCameraCharacteristics("0").Get(CameraCharacteristics.FlashInfoAvailable);
cameraManager.RegisterTorchCallback(new MyTorchRegister(), null);
if (MyTorchRegister.isFlashlightOn)
MainActivity.switch1.Checked = false;
// Toast.MakeText(context, "FlashLight is disabled", ToastLength.Long).Show();
else
MainActivity.switch1.Checked = true;
// Toast.MakeText(context, "FlashLight is Opened", ToastLength.Long).Show();
internal class MyTorchRegister : CameraManager.TorchCallback
public static bool isFlashlightOn = false;
public override void OnTorchModeChanged(string cameraId, bool enabled)
base.OnTorchModeChanged(cameraId, enabled);
isFlashlightOn = enabled;
这里是 XAndroidBroadcastRece 演示代码
Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch1);
//Setting the intial status of the switch to be unchecked by default
switch1.Checked = false;
//Adding delegate method to handle switch checked event
switch1.CheckedChange += delegate (object sender, CompoundButton.CheckedChangeEventArgs e)
if (e.IsChecked == true)
//Switch is on so turn on Flahlight
Flashlight.TurnOnAsync();
Intent intent = new Intent();
intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
SendBroadcast(intent);
Toast.MakeText(Application.Context, "Switch is ON", ToastLength.Long).Show();
else
//Switch is unchecked so turn off flashlight
Flashlight.TurnOffAsync();
Intent intent = new Intent();
intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
SendBroadcast(intent);
Toast.MakeText(Application.Context, "Switch is OFF", ToastLength.Long).Show();
;
【讨论】:
代码很长,但我会尝试应用它,看看是否能得到一些结果以上是关于检测闪光灯是不是已经打开的主要内容,如果未能解决你的问题,请参考以下文章