Skip to content

Commit

Permalink
Download data from the Internet and parse it.
Browse files Browse the repository at this point in the history
Added textviewes that showed information about source.
  • Loading branch information
Airat1995 committed Jun 24, 2016
1 parent 137a455 commit 09dbd05
Show file tree
Hide file tree
Showing 8 changed files with 204 additions and 23 deletions.
6 changes: 6 additions & 0 deletions ListenRadio/ListenRadio.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@
<ItemGroup>
<Reference Include="Mono.Android" />
<Reference Include="mscorlib" />
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.8.0.3\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
Expand All @@ -52,10 +56,12 @@
<Compile Include="MainActivity.cs" />
<Compile Include="Resources\Resource.Designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StreamInfo.cs" />
<Compile Include="StreamService.cs" />
</ItemGroup>
<ItemGroup>
<None Include="GettingStarted.Xamarin" />
<None Include="packages.config" />
<None Include="Resources\AboutResources.txt" />
<None Include="Assets\AboutAssets.txt" />
</ItemGroup>
Expand Down
75 changes: 70 additions & 5 deletions ListenRadio/MainActivity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,24 @@
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Net;
using Android.Util;
using System.Threading;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;

namespace ListenRadio
{
[Activity(Label = "ListenRadio", MainLauncher = true, Icon = "@drawable/icon")]
[Activity(Label = "ListenRadio", MainLauncher = true, Icon = "@drawable/icon", ConfigurationChanges = Android.Content.PM.ConfigChanges.KeyboardHidden | Android.Content.PM.ConfigChanges.Keyboard | Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
public class MainActivity : Activity
{
int count = 1;
/// <summary>
/// Used for get info from Source ancestor value, if with 0 will be null, then icrease them.
/// </summary>
private int _sourcepath = 0;

private TextView titleTextView;
private TextView infoTextView;

protected override void OnCreate(Bundle bundle)
{
Expand All @@ -20,22 +31,76 @@ protected override void OnCreate(Bundle bundle)
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);

// Get our button from the layout resource,
// and attach an event to it
Button playButton = FindViewById<Button>(Resource.Id.PlayButton);
Button stopButton = FindViewById<Button>(Resource.Id.StopButton);
Button pauseButton = FindViewById<Button>(Resource.Id.StopButton);

playButton.Click += delegate { SendAudioCommand(StreamService.ActionPlay); };
stopButton.Click += delegate { SendAudioCommand(StreamService.ActionStop); };
stopButton.Click += delegate { SendAudioCommand(StreamService.ActionStop); };

titleTextView = FindViewById<TextView>(Resource.Id.TitleTextView);
infoTextView = FindViewById<TextView>(Resource.Id.InfoTextView);
MakeRequest();
//TODO: make service delete this!!
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = 5000;
t.Elapsed += new System.Timers.ElapsedEventHandler(UpdateSourceData);
t.Start();

}

private void SendAudioCommand(string action)
{
var intent = new Intent(action);
intent.PutExtra("id", Resource.String.RadioUrl);
StartService(intent);
}

//Get request from server
protected void UpdateSourceData(object sender, System.Timers.ElapsedEventArgs e)
{
MakeRequest();
//To decrease threads. Should work.
Task.Delay(10000).Wait();
}

public void MakeRequest()
{
WebClient client = new WebClient();
string downloadedString = client.DownloadString(@"http://stream.sunlife-fm.org:8000/status-json.xsl");
var jsonObject = JObject.Parse(downloadedString);
var sourcedata = jsonObject.Root.SelectToken($"icestats.source[{_sourcepath}]");

//Check if first source data is empty, then its not work. Then mean it should get data from second source ancestor
if (sourcedata.SelectToken("title") == null && _sourcepath == 0)
{
_sourcepath = 1;
downloadedString = client.DownloadString(@"http://stream.sunlife-fm.org:8000/status-json.xsl");
jsonObject = JObject.Parse(downloadedString);
sourcedata = jsonObject.Root.SelectToken($"icestats.source[{_sourcepath}]");
}
RunOnUiThread(() => {
if (_sourcepath == 0)
FillFirstTypeInfo(sourcedata.SelectToken("bitrate").ToString(), sourcedata.SelectToken("channels").ToString(), sourcedata.SelectToken("samplerate").ToString());
else
FillSecondTypeInfo(sourcedata.SelectToken("audio_info").ToString());
titleTextView.SetText(sourcedata.SelectToken("title").ToString(), TextView.BufferType.Spannable);
});
Log.Debug("userdata", sourcedata.ToString());
}

public void FillFirstTypeInfo(string bitrate, string channels, string samplerate)
{
string info = $"bitrate={bitrate} channels={channels} samplerate={samplerate}";
infoTextView.SetText(info, TextView.BufferType.Spannable);
}

public void FillSecondTypeInfo(string audio_info)
{
string info = audio_info.ToString().Replace(';', ' ');
infoTextView.SetText(info, TextView.BufferType.Spannable);
}

protected override void OnDestroy()
{
var intent = new Intent(StreamService.ActionStop);
Expand Down
16 changes: 14 additions & 2 deletions ListenRadio/Resources/Resource.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 26 additions & 4 deletions ListenRadio/Resources/layout/Main.axml
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout1">
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="fill_parent"
android:layout_height="180dp"
android:scaleType="fitCenter"
android:id="@+id/LogoImageView" />
<TextView
android:text="Title"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/LogoImageView"
android:id="@+id/TitleTextView"
android:lines="1" />
<TextView
android:text="info"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/TitleTextView"
android:id="@+id/InfoTextView" />
<Button
android:id="@+id/PlayButton"
android:layout_below="@id/InfoTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Play" />
<Button
android:id="@+id/StopButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Stop" />
</LinearLayout>
android:text="@string/Stop"
android:layout_below="@id/PlayButton" />
</RelativeLayout>
1 change: 1 addition & 0 deletions ListenRadio/Resources/values/Strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
<string name="Stop">Stop radio</string>
<string name="Pause">Pause radio</string>
<string name="ApplicationName">ListenRadio</string>
<string name="RadioUrl">http://5.9.135.213:8000/play</string>
</resources>
59 changes: 59 additions & 0 deletions ListenRadio/StreamInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Net;

namespace ListenRadio
{
class StreamInfo
{
/// <summary>
/// Used for get stream info
/// </summary>
private WebClient _client;

/// <summary>
/// Stream info if requset complete without errors
/// </summary>
private string _data;
public string GetData()
{
return _data;
}

/// <summary>
/// Used when server return error to user
/// </summary>
private string _errorString;
public string GetError()
{
return _errorString;
}

public StreamInfo(string url)
{
_client = new WebClient();
_client.DownloadStringAsync(new Uri(url));
_client.DownloadStringCompleted += StreamDataGet;
}

private void StreamDataGet(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
_data = e.Result;
else
{
_data = null;
_errorString = e.Error.Message;
}
}
}
}
36 changes: 24 additions & 12 deletions ListenRadio/StreamService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class StreamService : Service, AudioManager.IOnAudioFocusChangeListener
public const string ActionPause = "com.action.PAUSE";
public const string ActionStop = "com.action.STOP";

private const string _radio = @"http://5.9.135.213:8000/play";
private string _radio;

private MediaPlayer player;
private AudioManager audioManager;
Expand All @@ -38,6 +38,7 @@ public override void OnCreate()
base.OnCreate();
audioManager = (AudioManager)GetSystemService(AudioService);
wifiManager = (WifiManager)GetSystemService(WifiService);
_radio = GetString(Resource.String.RadioUrl);
}

public override IBinder OnBind(Intent intent)
Expand Down Expand Up @@ -121,22 +122,28 @@ private async void Play()

private void StartForeground()
{

//Intent for showing notification
var pendingIntent = PendingIntent.GetActivity(ApplicationContext, 0,
new Intent(ApplicationContext, typeof(MainActivity)),
PendingIntentFlags.UpdateCurrent);

var notification = new Notification
{
TickerText = new Java.Lang.String("Stream started!"),
Icon = Resource.Drawable.Icon
};
notification.Flags |= NotificationFlags.OngoingEvent;
notification.SetLatestEventInfo(ApplicationContext, "Listen Radio",
"Music streaming", pendingIntent);
StartForeground(NotificationId, notification);
//Custom notification and build it
var builder = new Notification.Builder(this)
.SetContentText("Radio is playing")
.SetContentTitle("Listen Radio")
.SetContentIntent(pendingIntent)
.SetSmallIcon(Resource.Drawable.Icon)
.SetOngoing(true);
Notification notification = builder.Build();

//Init notification manager and show notification
NotificationManager notificationManager =
GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager.Notify(NotificationId, notification);

}

//Pause, can use it if you want
private void Pause()
{
if (player == null)
Expand All @@ -149,6 +156,7 @@ private void Pause()
paused = true;
}

//Stop
private void Stop()
{
if (player == null)
Expand All @@ -163,7 +171,7 @@ private void Stop()
ReleaseWifiLock();
}


//Wifi lockers, when device go to sleep still play streaming
private void AquireWifiLock()
{
if (wifiLock == null)
Expand Down Expand Up @@ -193,6 +201,10 @@ public override void OnDestroy()
}


/// <summary>
/// Focus change, when user change application
/// </summary>
/// <param name="focusChange">Check app audio focus</param>
public void OnAudioFocusChange(AudioFocus focusChange)
{
switch (focusChange)
Expand Down
4 changes: 4 additions & 0 deletions ListenRadio/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="8.0.3" targetFramework="monoandroid60" />
</packages>

0 comments on commit 09dbd05

Please sign in to comment.