Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检测闪光灯是否已打开_C#_Android_Xamarin_Flashlight - Fatal编程技术网

C# 检测闪光灯是否已打开

C# 检测闪光灯是否已打开,c#,android,xamarin,flashlight,C#,Android,Xamarin,Flashlight,我有一个简单的切换开关,打开和关闭手电筒的应用程序,我需要的代码,我可以用来检查手电筒是否已经打开,然后使用它来改变开关的切换状态。。。 如果服务报告手电筒亮了,我会发送一个广播意图将其关闭,反之亦然。。。我的应用程序逻辑在这里 class SecondActivity : AppCompatActivity{ protected override void OnCreate(Bundle onSavedInstanceState){ //Switch definition

我有一个简单的切换开关,打开和关闭手电筒的应用程序,我需要的代码,我可以用来检查手电筒是否已经打开,然后使用它来改变开关的切换状态。。。 如果服务报告手电筒亮了,我会发送一个广播意图将其关闭,反之亦然。。。我的应用程序逻辑在这里

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
        }

}
用户可以在应用程序外打开手电筒,因此我只需要该代码来检查其是否已打开,然后我将实现广播意图以适当地更改我的开关,感谢您的时间和贡献

用户可以在应用程序外打开手电筒,因此我只需要该代码来检查其是否已打开,然后我将实现广播意图以适当地更改我的开关

你想达到下面的效果吗

我要实现两个应用程序:

MyForegroundServiceDemo:如果启用或不启用,则使用广播来显示或使用手电筒,以使广播接收器始终在后台或前台运行,我使用forground服务来实现它。然后在前台服务中注册广播接收器

xandroid:只需打开/关闭手电筒

这是我的MyForegroundServiceDemo代码

首先,您需要在AndroidManifest.xml中添加和使用grand Camera&Flashlight权限

然后,这里是我的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_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Please see following switch"/>
<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
        android:id="@+id/switch1"/>
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button1" 
        android:text="start"/>

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button2" 
        android:text="Stop"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="123@456"/>
</LinearLayout>
下面是关于MyForegroundService.cs的代码。当我们在MyReceiverBroadcastReceiver中接收广播时,我们会使用MyTorchRegister记录手电筒的状态

下面是XAndroidBroadcastRece演示代码

用户可以在应用程序外打开手电筒,因此我只需要该代码来检查其是否已打开,然后我将实现广播意图以适当地更改我的开关

你想达到下面的效果吗

我要实现两个应用程序:

MyForegroundServiceDemo:如果启用或不启用,则使用广播来显示或使用手电筒,以使广播接收器始终在后台或前台运行,我使用forground服务来实现它。然后在前台服务中注册广播接收器

xandroid:只需打开/关闭手电筒

这是我的MyForegroundServiceDemo代码

首先,您需要在AndroidManifest.xml中添加和使用grand Camera&Flashlight权限

然后,这里是我的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_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Please see following switch"/>
<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
        android:id="@+id/switch1"/>
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button1" 
        android:text="start"/>

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/button2" 
        android:text="Stop"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="123@456"/>
</LinearLayout>
下面是关于MyForegroundService.cs的代码。当我们在MyReceiverBroadcastReceiver中接收广播时,我们会使用MyTorchRegister记录手电筒的状态

下面是XAndroidBroadcastRece演示代码


手电筒似乎只支持TurnOnAsync和TurnOffAsync。因此,考虑到您只想使用此API,我会在一开始将灯光设置为定义的状态,例如,关闭灯光,而不管其当前状态如何。在我更新的答案中,这是否有效?好的,听起来是一个很酷的主意,对我来说太不幸了。如果我现在去playstore并安装蓝牙应用程序,不知何故,如果我从外部触发器启用蓝牙,这些应用程序将知道并对UI进行必要的更改。。蓝牙有那个服务来检查它的状态吗?@Fildor,好的,我需要弄清楚out@Fildor,感谢您下载的progressFlashlight似乎只支持TurnOnAsync和TurnOffAsync。因此,考虑到您只想使用此API,我会在一开始将灯光设置为定义的状态,例如,关闭灯光,而不管其当前状态如何。在我更新的答案中,这是否有效?好的,听起来是一个很酷的主意,对我来说太不幸了。如果我现在去playstore并安装蓝牙应用程序,不知何故,如果我从外部触发器启用蓝牙,这些应用程序将知道并对UI进行必要的更改。。蓝牙有那个服务来检查它的状态吗?@Fildor,好的,我需要弄清楚out@Fildor,感谢您在progressCode中的下载。代码很长,但我会尝试应用它并查看是否得到一些结果。代码很长,但我会尝试应用它并查看是否得到一些结果
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;

            }
        }
    }

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