Showing posts with label Windows Phone. Show all posts
Showing posts with label Windows Phone. Show all posts

Sunday, 9 October 2016

Different Way to Use Back Button Event in Windows Phone 8.1

This code snippet for User back button in windows phone according to your requirement.


Different ways to use Back Button press event in windows phone:

1. Using hardware button event (It will fire from all pages of application while you write event on a single page)

HardwareButtons.BackPressed += HardwareButtons_BackPressed; event
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)  
{  
  
   Application.Current.Exit();  
  
}  


2. If you want back button will work on any individual page then use following method.
protected override void OnNavigatedFrom(NavigationEventArgs e)  
{  
    this.navigationHelper.OnNavigatedFrom(e);  
  
    base.OnNavigatedFrom(e);  
  
    if (e.NavigationMode == NavigationMode.Back)  
    {  
        App.Current.Exit();  
    }  
  
}  


3. To override button event in windows phone device.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)  
  
{  
  
    e.Cancel = true;  
  
    base.OnBackKeyPress(e);  
  
}  
When we uses first method then it will fire (close the application) form any page. Means event will fire from all page when back button pressed. But if we want that will work on any particular page the 2nd method will be the best.

Code For Check Headphone Jack is Connected form Windows Phone Device or Not

This demo checking whether headphone jack is connected form Windows phone device or not. We are also checking the audio (.MP3) sound from earpiece and device loudspeaker in WP8.1

MainPage.xaml
----------------------
<phone:PhoneApplicationPage x:Class="TstApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:drawerLayout="using:DrawerLayout" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True">
    <Grid x:Name="LayoutRoot" Background="LightGray">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" /> </Grid.RowDefinitions>
        <MediaElement x:Name="playbackElement1" Source="basictone.mp3" AutoPlay="False"></MediaElement>
        <TextBlock Name="scanComp" Foreground="BlueViolet" TextAlignment="Center" FontSize="30" Text="..." Height="95" Margin="0,53,0,352"></TextBlock>
        <TextBlock Name="scanComp1" Foreground="BlueViolet" TextAlignment="Center" FontSize="24" Text="..." Height="95"></TextBlock>
        <TextBlock Name="scanComp2" Foreground="BlueViolet" TextAlignment="Center" FontSize="30" Text="0" Height="95" Margin="0,386,0,19"></TextBlock>
        <Popup VerticalOffset="10" x:Name="JackPopup" IsOpen="False" Margin="28,235,62,265">
            <Border BorderThickness="2" Width="387" Height="254" Margin="0,0,0,0">
                <StackPanel Background="Gray" VerticalAlignment="Center" Height="216" Margin="12,17,-12,17">
                    <StackPanel Margin="14,0,-4,0" Orientation="Horizontal">
                        <TextBlock Text="Alert" Margin="30,2,2,10" HorizontalAlignment="Left" FontSize="36" Height="51" Width="189" /> </StackPanel>
                    <TextBlock Text="Unable to detect headphone. Plese connect and click Retry." Margin="0,10,0,0" TextWrapping="Wrap" FontSize="22" HorizontalAlignment="Right" Width="332" Height="67" />
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="20,0,2,2" Height="69">
                        <Button Content="Skip" Click="SkipJackPopupClicked" Width="150" />
                        <Button Content="Retry" Click="RetryJackPopupClicked" Width="150" /> </StackPanel>
                </StackPanel>
            </Border>
        </Popup>
        <Popup VerticalOffset="10" x:Name="EarpiecePopup" IsOpen="False" Margin="28,235,62,265">
            <Border BorderThickness="2" Width="387" Height="254" Margin="0,0,0,0">
                <StackPanel Background="Gray" VerticalAlignment="Center" Height="216">
                    <StackPanel Margin="14,0,-4,0" Orientation="Horizontal">
                        <TextBlock Text="Alert" Margin="30,2,2,10" HorizontalAlignment="Left" FontSize="36" Height="51" Width="189" /> </StackPanel>
                    <TextBlock Text="Unable to detect headphone. Please connect and click Retry." Margin="0,10,0,0" TextWrapping="Wrap" FontSize="22" HorizontalAlignment="Right" Width="332" Height="67" />
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="20,0,2,2" Height="69">
                        <Button Content="Skip" Click="SkipEarpiecePopupClicked" Width="150" />
                        <Button Content="Retry" Click="RetryEarpiecePopupClicked" Width="150" /> </StackPanel>
                </StackPanel>
            </Border>
        </Popup>
        <Popup VerticalOffset="10" x:Name="EarpieceSoundPopup" IsOpen="False" Margin="28,235,62,265">
            <Border BorderThickness="2" Width="387" Height="254" Margin="0,0,0,0">
                <StackPanel Background="Gray" VerticalAlignment="Center" Height="216">
                    <StackPanel Margin="14,0,-4,0" Orientation="Horizontal">
                        <TextBlock Text="Earpiece Audio" Margin="30,2,2,10" HorizontalAlignment="Left" FontSize="36" Height="51" Width="244" /> </StackPanel>
                    <TextBlock Text="Where you able to hear audio clearly? Plese open the earpiece jack and click Yes/No." Margin="0,5,0,0" TextWrapping="Wrap" FontSize="22" HorizontalAlignment="Right" Width="332" Height="91" />
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="20,0,2,2" Height="69">
                        <Button Content="Yes" Click="YesPopupClicked" Width="150" />
                        <Button Content="No" Click="NoPopupClicked" Width="150" /> </StackPanel>
                </StackPanel>
            </Border>
        </Popup>
        <Popup VerticalOffset="10" x:Name="LoudspeakerSoundPopup" IsOpen="False" Margin="28,235,62,265">
            <Border BorderThickness="2" Width="387" Height="254" Margin="0,0,0,0">
                <StackPanel Background="Gray" VerticalAlignment="Center" Height="216">
                    <StackPanel Margin="14,0,-4,0" Orientation="Horizontal">
                        <TextBlock Text="Speaker Audio" Margin="30,2,2,10" HorizontalAlignment="Left" FontSize="36" Height="51" Width="259" /> </StackPanel>
                    <TextBlock Text="Where you able to hear audio clearly?" Margin="0,10,0,0" TextWrapping="Wrap" FontSize="22" HorizontalAlignment="Right" Width="332" Height="67" />
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="20,0,2,2" Height="69">
                        <Button Content="Yes" Click="LoudspeakerYesPopupClicked" Width="150" />
                        <Button Content="No" Click="LoudspeakerNoPopupClicked" Width="150" /> </StackPanel>
                </StackPanel>
            </Border>
        </Popup>
    </Grid>
</phone:PhoneApplicationPage>



MainPage.xaml.cs

-----------------------
namespace TstApp {
    public partial class MainPage: PhoneApplicationPage {
        DispatcherTimer headphoneTimer;
        DispatcherTimer speakerTimer;
        int currentcount = 0;
        public MainPage() {
            InitializeComponent();
            AudioRoutingManager.GetDefault().AudioEndpointChanged += AudioEndpointChanged;
            var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
            roamingSettings.Values["cntearpiece"] = 0;
            roamingSettings.Values["cntJack"] = 0;
            headphoneTimer = new DispatcherTimer();
            headphoneTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
            headphoneTimer.Tick += new EventHandler(headphoneTimer_Tick);
            speakerTimer = new DispatcherTimer();
            speakerTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
            speakerTimer.Tick += new EventHandler(speakerTimer_Tick);
            checkHeadphoneJack();
        }
        private void headphoneTimer_Tick(object sender, EventArgs e) {
            scanComp2.Text = currentcount--.ToString();
            string str = Convert.ToString(AudioRoutingManager.GetDefault().GetAudioEndpoint());
            if (str != "Speakerphone") {
                headphoneTimer.Stop();
                EarpiecePopup.IsOpen = true;
                ScanHeadphneSpeakerStart();
            }
            if (currentcount <= 0) {
                var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
                object cntJack = roamingSettings.Values["cntJack"];
                if (Convert.ToInt32(cntJack) == 1) {
                    headphoneTimer.Stop();
                    ScanHeadphneSpeakerStart();
                } else {
                    headphoneTimer.Stop();
                    JackPopup.IsOpen = true;
                }
            }
        }
        private void speakerTimer_Tick(object sender, EventArgs e) {
            scanComp2.Text = currentcount--.ToString();
            string str = Convert.ToString(AudioRoutingManager.GetDefault().GetAudioEndpoint());
            if (str != "Speakerphone") {
                speakerTimer.Stop();
                EarpiecePopup.IsOpen = true;
                ScanHeadphneSpeakerStart();
            }
            if (currentcount <= 0) {
                var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
                object cntearpiece = roamingSettings.Values["cntearpiece"];
                if (Convert.ToInt32(cntearpiece) == 1) {
                    speakerTimer.Stop();
                    ScanHeadphneSpeakerStart();
                } else {
                    speakerTimer.Stop();
                    EarpiecePopup.IsOpen = true;
                }
            }
        }
        public void AudioEndpointChanged(AudioRoutingManager sender, object args) {
            // ScanHeadphneSpeakerStart();
        }
        protected void checkHeadphoneJack() {
            scanComp.Text = "Scaning Headphone jack";
            string str = Convert.ToString(AudioRoutingManager.GetDefault().GetAudioEndpoint());
            if (str == "Speakerphone") {
                scanComp1.Text = "Please connect 3.5 mm jack.";
                currentcount = 10;
                headphoneTimer.Start();
            } else {
                ScanHeadphneSpeakerStart();
            }
        }
        protected async void ScanHeadphneSpeakerStart() {
            scanComp.Text = "Scanning Earpiece";
            string str = Convert.ToString(AudioRoutingManager.GetDefault().GetAudioEndpoint());
            var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
            object cntearpiece = roamingSettings.Values["cntearpiece"];
            if (str == "Speakerphone" && Convert.ToInt32(cntearpiece) == 0) {
                scanComp1.Text = "Please attach headphone jack.";
                currentcount = 10;
                speakerTimer.Start();
            } else if (str == "Speakerphone" && Convert.ToInt32(cntearpiece) == 1) {
                loudSpeakerStart();
                // Code for Earpiece slound fail.
            } else {
                playbackElement1.Stop();
                playbackElement1.AutoPlay = true;
                playbackElement1.Play();
                await Task.Delay(TimeSpan.FromSeconds(1));
                EarpieceSoundPopup.IsOpen = true;
            }
        }
        protected async void playEarpeceSound() {
            playbackElement1.Stop();
            playbackElement1.AutoPlay = true;
            playbackElement1.Play();
            await Task.Delay(TimeSpan.FromSeconds(1));
            EarpieceSoundPopup.IsOpen = true;
        }
        protected async void loudSpeakerStart() {
            playbackElement1.Stop();
            playbackElement1.AutoPlay = false;
            await Task.Delay(TimeSpan.FromSeconds(5));
            playbackElement1.AutoPlay = true;
            playbackElement1.Play();
            await Task.Delay(TimeSpan.FromSeconds(3));
            LoudspeakerSoundPopup.IsOpen = true;
        }
        protected void SkipJackPopupClicked(object sender, RoutedEventArgs e) {
            JackPopup.IsOpen = false;
            headphoneTimer.Stop();
            ScanHeadphneSpeakerStart();
        }
        protected void RetryJackPopupClicked(object sender, RoutedEventArgs e) {
            JackPopup.IsOpen = false;
            var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
            roamingSettings.Values["cntJack"] = 1;
            currentcount = 10;
            headphoneTimer.Start();
        }
        protected void YesPopupClicked(object sender, RoutedEventArgs e) {
            EarpieceSoundPopup.IsOpen = false;
            loudSpeakerStart();
        }
        protected void NoPopupClicked(object sender, RoutedEventArgs e) {
            EarpieceSoundPopup.IsOpen = false;
            loudSpeakerStart();
        }
        protected void SkipEarpiecePopupClicked(object sender, RoutedEventArgs e) {
            EarpiecePopup.IsOpen = false;
            speakerTimer.Stop();
            ScanHeadphneSpeakerStart();
        }
        protected void RetryEarpiecePopupClicked(object sender, RoutedEventArgs e) {
            EarpiecePopup.IsOpen = false;
            var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
            roamingSettings.Values["cntearpiece"] = 1;
            currentcount = 10;
            speakerTimer.Start();
        }
        protected void LoudspeakerYesPopupClicked(object sender, RoutedEventArgs e) {
            LoudspeakerSoundPopup.IsOpen = false;
            NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
        }
        protected void LoudspeakerNoPopupClicked(object sender, RoutedEventArgs e) {
            LoudspeakerSoundPopup.IsOpen = false;
            NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
        }
    }
}

Saturday, 26 December 2015

Reading Image and Video from device in windows phone 8.1

1.  Create a button control in Xaml page.

MainPage.Xaml
 <Button x:Name="btnPhotos" HorizontalAlignment="Left" Margin="2,256,0,0" VerticalAlignment="Top" FontFamily="Arial" Width="388" Height="96" Click="btnPhotos_Click">
            <TextBlock x:Name="textBlock" Text="Photos" FontSize="28" Foreground="#FF7A7070"  Width="210" Height="42"/>
 </Button>
 <Button x:Name="btnVideo" HorizontalAlignment="Left" Height="99" Margin="3,366,0,0" VerticalAlignment="Top" FontFamily="Arial" Width="387" Click="btnVideo_Click">
            <TextBlock Name="textVideo" Text="Video" FontSize="28" Margin="10,0,23,0" Foreground="#FF7A7070" Width="210" Height="42"></TextBlock>
 </Button>

2. Write the following code on code behind.
MainPage.Xaml.cs
========================
 private async void btnPhotos_Click(object sender, RoutedEventArgs e)
        {
            photosProgressBar.Visibility = Visibility.Visible;
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.PickMultipleFilesAndContinue();
        }

 private async void btnVideo_Click(object sender, RoutedEventArgs e)
        {
            videoProgressBar.Visibility = Visibility.Visible;
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".mp4");
            //openPicker.FileTypeFilter.Add(".jpeg");
            //openPicker.FileTypeFilter.Add(".png");
            openPicker.PickMultipleFilesAndContinue();
        }

 public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            IReadOnlyList<StorageFile> files = args.Files;
            if (files.Count > 0)
            {

                foreach (var item in files)
                {
   //Do your work                  
                }
            }
        }

3. Write an event in App.Xaml.cs.
App.Xaml.cs
===========================
  protected override void OnActivated(IActivatedEventArgs args)
        {
           // Sync osync = new Sync();
            var root = Window.Current.Content as Frame;
            var sync = root.Content as Sync;
            if (sync != null && args is FileOpenPickerContinuationEventArgs)
            {
                sync.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
            }
        }
      

Voice Recording/Mic Testing and Playing Recorded Sound in Windows Phone Silverlight

<phone:PhoneApplicationPage x:Class="MicrophoneTest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True">  
  1.     <!--LayoutRoot is the root grid where all page content is placed-->  
  2.     <Grid x:Name="LayoutRoot" Background="LightBlue">  
  3.         <Image x:Name="ScanComp" HorizontalAlignment="Left" Height="170" Margin="156,235,0,0" VerticalAlignment="Top" Width="170" />  
  4.         <TextBlock Name="timerMsg" Margin="10,460,10,257" TextAlignment="Center" Foreground="White" FontSize="24"></TextBlock>  
  5.         <TextBlock Name="timedisplayBlock" Margin="206,508,221,209" Foreground="White" FontSize="40"></TextBlock>  
  6.         <Button Name="btnstart" Content="start" Click="recordButton_Click" Margin="0,636,0,58"></Button>  
  7.     </Grid>  
  8. </phone:PhoneApplicationPage> 
  1. public partial class MainPage: PhoneApplicationPage  

  2. {  
  3.     // Constructor  
  4.     int currentcount;  
  5.     Microphone microphone = Microphone.Default;  
  6.     byte[] buffer;  
  7.     MemoryStream stream = new MemoryStream();  
  8.     SoundEffect sound;  
  9.     DispatcherTimer recordingTimer;  
  10.     public MainPage()  
  11.     {  
  12.         InitializeComponent();  
  13.         recordingTimer = new DispatcherTimer();  
  14.         recordingTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);  
  15.         recordingTimer.Tick += new EventHandler(recordingTimer_Tick);  
  16.     }  
  17.     private void recordButton_Click(object sender, EventArgs e)  
  18.     {  
  19.         Startrecording();  
  20.     }  
  21.     protected async void Startrecording()  
  22.     {  
  23.         ScanComp.Source = new BitmapImage(new Uri(@ "Assets/scan_microphone.png", UriKind.Relative));  
  24.         timerMsg.Text = "Speak something to test recording.";  
  25.         currentcount = 10;  
  26.         recordingTimer.Start();  
  27.         DispatcherTimer dt = new DispatcherTimer();  
  28.         dt.Interval = TimeSpan.FromMilliseconds(33);  
  29.         dt.Tick += delegate  
  30.         {  
  31.             try  
  32.             {  
  33.                 FrameworkDispatcher.Update();  
  34.             }  
  35.             catch  
  36.             {}  
  37.         };  
  38.         dt.Start();  
  39.         microphone.BufferReady += new EventHandler < EventArgs > (microphone_BufferReady);  
  40.         microphone.BufferDuration = TimeSpan.FromMilliseconds(1000);  
  41.         buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];  
  42.         microphone.Start();  
  43.         await Task.Delay(TimeSpan.FromSeconds(10));  
  44.         if (microphone.State == MicrophoneState.Started)  
  45.         {  
  46.             microphone.Stop();  
  47.         }  
  48.         timerMsg.Text = "playing sound...";  
  49.         sound = new SoundEffect(stream.ToArray(), microphone.SampleRate, AudioChannels.Mono);  
  50.         sound.Play();  
  51.     }  
  52.     void microphone_BufferReady(object sender, EventArgs e)  
  53.     {  
  54.         microphone.GetData(buffer);  
  55.         stream.Write(buffer, 0, buffer.Length);  
  56.     }  
  57.     private void recordingTimer_Tick(object sender, EventArgs e)  
  58.     {  
  59.         timedisplayBlock.Text = currentcount--.ToString();  
  60.         if (currentcount == 0)  
  61.         {  
  62.             recordingTimer.Stop();  
  63.             timedisplayBlock.Text = "";  
  64.             timerMsg.Text = "playing sound...";  
  65.         }  
  66.     }  
  67. }  

Windows Phone Device Mode and Version in windows phone Silverlight 8.1.

  1. public MainPage()  
  2. {  
  3.     InitializeComponent();  
  4.     var phone = PhoneNameResolver.Resolve(DeviceStatus.DeviceManufacturer, DeviceStatus.DeviceName);  
  5.     txtModel.Text = Convert.ToString(phone.FullCanonicalName);  
  6.     txtVrsn.Text = Convert.ToString(System.Environment.OSVersion);  
  7.   
  8.      
  9. }  http://www.c-sharpcorner.com/code/2075/windows-phone-device-model-and-version-in-windows-phone-silv.aspx