Skip to content

Commit

Permalink
Replaced services with Jobs for Android notifications and fixed other…
Browse files Browse the repository at this point in the history
… errors
  • Loading branch information
Noc2 committed Apr 10, 2018
1 parent cf999fa commit 333efc2
Show file tree
Hide file tree
Showing 23 changed files with 359 additions and 336 deletions.
7 changes: 2 additions & 5 deletions Chiota/Chiota.Android/Chiota.Android.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,6 @@
<PackageReference Include="Xam.Plugins.Forms.ImageCircle">
<Version>2.0.2</Version>
</PackageReference>
<PackageReference Include="Xam.Plugins.Notifier">
<Version>3.0.0-beta14</Version>
</PackageReference>
<PackageReference Include="Xamarin.Forms" Version="2.5.1.444934" />
<PackageReference Include="Xamarin.Android.Support.Design" Version="26.1.0.1" />
<PackageReference Include="Xamarin.Android.Support.v7.AppCompat" Version="26.1.0.1" />
Expand All @@ -114,8 +111,8 @@
<Compile Include="Resources\Resource.Designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Renderer\Scrollbardisabledrenderer.cs" />
<Compile Include="Services\BackgroundReceiver.cs" />
<Compile Include="Services\PeriodicTaskService.cs" />
<Compile Include="Services\NotificationsTask.cs" />
<Compile Include="Services\PeriodicJob.cs" />
<Compile Include="SplashActivity.cs" />
</ItemGroup>
<ItemGroup>
Expand Down
54 changes: 21 additions & 33 deletions Chiota/Chiota.Android/MainActivity.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
namespace Chiota.Droid
{
using Android.App;
using Android.App.Job;
using Android.Content;
using Android.Content.PM;
using Android.OS;

using Chiota;
using Chiota.Droid.Services;
using Chiota.Messages;
using ImageCircle.Forms.Plugin.Droid;

using Plugin.LocalNotifications;
using ImageCircle.Forms.Plugin.Droid;

using Plugin.Permissions;

using Xamarin.Forms;

[Activity(Label = "FlorenceApp", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[Activity(Label = "Chiota", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
private JobScheduler jobScheduler;

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
Expand All @@ -27,45 +34,26 @@ protected override void OnCreate(Bundle bundle)
// ToolbarResource = Resource.Id.toolbar;
base.OnCreate(bundle);

Xamarin.Forms.Forms.Init(this, bundle);
Forms.Init(this, bundle);

this.jobScheduler = (JobScheduler)this.GetSystemService(JobSchedulerService);

ZXing.Net.Mobile.Forms.Android.Platform.Init();

ImageCircleRenderer.Init();

// Changes the notification icon
LocalNotificationsImplementation.NotificationIconId = Resource.Drawable.reminder;

this.LoadApplication(new App());
this.WireUpLongRunningTask();
}

// https://github.com/jamesmontemagno/MediaPlugin#important-permission-information
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
private void WireUpLongRunningTask()
{
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

public void WireUpLongRunningTask()
{
MessagingCenter.Subscribe<StartLongRunningTaskMessage>(
this,
"StartLongRunningTaskMessage",
message =>
{
var intent = new Intent(this, typeof(PeriodicTaskService));
this.StartService(intent);
});

MessagingCenter.Subscribe<StopLongRunningTaskMessage>(
this,
"StopLongRunningTaskMessage",
message =>
{
var intent = new Intent(this, typeof(PeriodicTaskService));
this.StopService(intent);
});
var javaClass = Java.Lang.Class.FromType(typeof(PeriodicJob));
var compName = new ComponentName(this, javaClass);
var jobInfo = new JobInfo.Builder(1, compName)
.SetRequiredNetworkType(NetworkType.Any)
.SetPeriodic(1000 * 60 * 15).Build();
var result = this.jobScheduler.Schedule(jobInfo);
}
}
}
4 changes: 2 additions & 2 deletions Chiota/Chiota.Android/Properties/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="2" android:versionName="0.2" package="ChiotaApp.ChiotaApp" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="3" android:versionName="0.21" package="ChiotaApp.ChiotaApp" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="24" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Expand Down
42 changes: 19 additions & 23 deletions Chiota/Chiota.Android/Resources/Resource.designer.cs

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

46 changes: 0 additions & 46 deletions Chiota/Chiota.Android/Services/BackgroundReceiver.cs

This file was deleted.

61 changes: 61 additions & 0 deletions Chiota/Chiota.Android/Services/NotificationsTask.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
namespace Chiota.Droid.Services
{
using System.Linq;
using System.Threading.Tasks;

using Android.App;
using Android.Content;
using Android.Media;
using Android.OS;
using Android.Support.V4.App;

using Chiota.Models;
using Chiota.Services;
using Java.Lang;

using Resource = Resource;

public class NotificationsTask : AsyncTask<Void, Void, Task<bool>>
{
protected override async Task<bool> RunInBackground(params Void[] @params)
{
var finished = await this.LookForNewNotifications();
return finished;
}

private async Task<bool> LookForNewNotifications()
{
// seed needs to be stored on device!!
var secureStorage = new SecureStorage();
if (secureStorage.CheckUserStored())
{
var user = await secureStorage.GetUser();
if (user != null)
{
var contactApprovedList = await user.TangleMessenger.GetJsonMessageAsync<SentDataWrapper<Contact>>(user.ApprovedAddress);

// currently no messages for contact request due to perfomance issues
foreach (var contact in contactApprovedList.Where(c => !c.Data.Rejected))
{
var encryptedMessages = await user.TangleMessenger.GetMessagesAsync(contact.Data.ChatAdress);

foreach (var unused in encryptedMessages.Where(c => !c.Stored))
{
var builder = new NotificationCompat.Builder(Application.Context)
.SetAutoCancel(true) // Dismiss from the notif. area when clicked
.SetContentTitle(contact.Data.Name) // Set its title
.SetContentText("New Message from " + contact.Data.Name)
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
.SetSmallIcon(Resource.Drawable.reminder);
var notification = builder.Build();
var notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager?.Notify(0, notification);
}
}
}
}

return true;
}
}
}
63 changes: 63 additions & 0 deletions Chiota/Chiota.Android/Services/PeriodicJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
namespace Chiota.Droid.Services
{
using System.Threading;
using System.Threading.Tasks;

using Android.App;
using Android.App.Job;
using Android.OS;

using Chiota.Messages;

using Xamarin.Forms;

[Service(Name = "ChiotaApp.ChiotaApp.PeriodicJob", Permission = "android.permission.BIND_JOB_SERVICE")]
public class PeriodicJob : JobService
{
private CancellationTokenSource cts;

public override bool OnStartJob(JobParameters jobParameters)
{
// Called by the operating system when starting the service.
// Start up a thread, do work on the thread.
this.cts = new CancellationTokenSource();

Task.Run(
() =>
{
try
{
var notification = new NotificationsTask();
notification.Execute();
}
catch (OperationCanceledException)
{
}
finally
{
if (this.cts.IsCancellationRequested)
{
var message = new CancelledMessage();
Device.BeginInvokeOnMainThread(() => MessagingCenter.Send(message, "CancelledMessage"));
}
}
},
this.cts.Token);

return true;
}

public override bool OnStopJob(JobParameters jobParameters)
{
// Called by Android when it has to terminate a running service.
if (this.cts != null)
{
this.cts.Token.ThrowIfCancellationRequested();

this.cts.Cancel();
}

return true; // false don't reschedule the job.
}
}
}
Loading

0 comments on commit 333efc2

Please sign in to comment.