Xamarin.Android : Problem using the library Zxing,Net.Mobile, error (Message=Resource ID #0x7f0a002a) in the debug before inflate the AXML - android-fragments

I have a problem using the library Zxing,Net.Mobile, want to have a popup (fragment) which reads a barcode, but in debug I get an error, I'm using the following repository as an example (https://github.com/Redth/ZXing.Net.Mobile/tree/master/Samples/Sample.Android), but when I run the code and click to open the fragment I get the following problem.
This is my AXML Activity (OrdersPatientsActivity)
When I click on the red highlighted button, it opens my popup (ScanBarcodeFragment), but in the Activity I initialise Zxing as follows (the final part):
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.LayoutListOrdenPatient);
searchBar = FindViewById<EditText>(Resource.Id.searchBarMainFilterCarMed);
llPatientInfo = FindViewById<LinearLayout>(Resource.Id.llPatientInfo);
PatientName = FindViewById<TextView>(Resource.Id.tvPatientNameCarMed);
IdentificationType = FindViewById<TextView>(Resource.Id.tvTDocumentoCarMed);
Identification = FindViewById<TextView>(Resource.Id.tvDocumentoCarMed);
Age = FindViewById<TextView>(Resource.Id.tvEdadCarMed);
HistoryNumber = FindViewById<TextView>(Resource.Id.tvHistoriaCarMed);
EntryNumber = FindViewById<TextView>(Resource.Id.tvNoIngresoCarMed);
Location = FindViewById<TextView>(Resource.Id.tvUbicacionCarMed);
btnExpandView = FindViewById<ImageButton>(Resource.Id.btnExpandView);
btnScanMed = FindViewById<ImageButton>(Resource.Id.btnScanMed);
ListMedicamentCarMed = FindViewById<ListView>(Resource.Id.ListMedicamentCarMed);
Save = FindViewById<Button>(Resource.Id.btnGuardar);
///vista cargando
var ProgressView = LayoutInflater.Inflate(Resource.Layout.LoadingDialogCharge, null);
TextView Msg = ProgressView.FindViewById<TextView>(Resource.Id.tvProgressDialogMsg);
Msg.Text = "Cargando informaciĆ³n de los cargos...";
animationscale = AnimationUtils.LoadAnimation(this, Resource.Drawable.Animationlogo);
LogoDialogProgress = ProgressView.FindViewById<ImageView>(Resource.Id.LogoDialogProgress);
progressDialog = (new AlertDialog.Builder(this, Resource.Style.ServinteDialog)).Create();
progressDialog.SetView(ProgressView);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);
btnScanMed.Click += BtnScanMed_Click;
}
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);
And in the click the ImageView is this:
try
{
StartActivity(typeof(ScanBarcodeFragment));
}
the fragment is exactly as in the example:
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZXing.Mobile;
namespace APPDroid.CarMed.Fragments
{
[Activity(Label = "ZXing.Net.Mobile", Theme = "#style/Theme.AppCompat.Light", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden)]
public class ScanBarcodeFragment : AndroidX.Fragment.App.FragmentActivity
{
#region Variables
ZXingScannerFragment scanFragment;
#endregion
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ScanBarcode);
}
protected override void OnResume()
{
base.OnResume();
if (scanFragment == null)
{
scanFragment = new ZXingScannerFragment();
SupportFragmentManager.BeginTransaction().Replace(Resource.Id.fragment_container, scanFragment).Commit();
}
Scan();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
=> Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
protected override void OnPause()
{
scanFragment?.StopScanning();
base.OnPause();
}
void Scan()
{
var opts = new MobileBarcodeScanningOptions
{
PossibleFormats = new List<ZXing.BarcodeFormat> {
ZXing.BarcodeFormat.QR_CODE
},
CameraResolutionSelector = availableResolutions =>
{
foreach (var ar in availableResolutions)
{
Console.WriteLine("Resolution: " + ar.Width + "x" + ar.Height);
}
return null;
}
};
scanFragment.StartScanning(result =>
{
// Null result means scanning was cancelled
if (result == null || string.IsNullOrEmpty(result.Text))
{
Toast.MakeText(this, "Scanning Cancelled", ToastLength.Long).Show();
return;
}
// Otherwise, proceed with result
RunOnUiThread(() => Toast.MakeText(this, "Scanned: " + result.Text, ToastLength.Short).Show());
}, opts);
}
}
}
But I get this error when I click on it:
when inflating the view all goes well, but when finishing the Scan() method; the problem occurs:
Android.Content.Res.Resources+NotFoundException Message=Resource ID #0x7f0a002a
Is it possible that I need an extra textview with a result ID?
Please I need help I have been trying to do barcode scanning for several days.

Related

Is there a way to use the camera functions in Xamarin Forms without downloading any extra NuGet Packages?

I am currently building a project which allows the user to take a photo of something and use that photo. I was wondering if there were any other methods out there that does not require me to download any Plugins or NuGet Packages?
You need to create a ICameraPickerService in Xamarin Forms :
public interface IPhotoPickerService
{
Task<byte[]> GetImageStreamAsync();
}
In iOS , create the CameraPickerService :
[assembly: Dependency(typeof(CameraPickerService))]
namespace DependencyServiceDemos.iOS
{
public class CameraPickerService: ICameraPickerService
{
TaskCompletionSource<byte[]> taskCompletionSource;
UIImagePickerController imagePicker;
public Task<byte[]> GetImageStreamAsync()
{
// Create and define UIImagePickerController
imagePicker = new UIImagePickerController
{
SourceType = UIImagePickerControllerSourceType.Camera,
MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera)
};
// Set event handlers
imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia;
imagePicker.Canceled += OnImagePickerCancelled;
// Present UIImagePickerController;
UIWindow window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
viewController.PresentModalViewController(imagePicker, true);
// Return Task object
taskCompletionSource = new TaskCompletionSource<byte[]>();
return taskCompletionSource.Task;
}
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
{
UIImage image = args.EditedImage ?? args.OriginalImage;
if (image != null)
{
// Convert UIImage to .NET Stream object
NSData data;
if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png"))
{
data = image.AsPNG();
}
else
{
data = image.AsJPEG(1);
}
Stream stream = data.AsStream();
UnregisterEventHandlers();
// Set the Stream as the completion of the Task
taskCompletionSource.SetResult(data.ToArray());
}
else
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
}
imagePicker.DismissModalViewController(true);
}
void OnImagePickerCancelled(object sender, EventArgs args)
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
imagePicker.DismissModalViewController(true);
}
void UnregisterEventHandlers()
{
imagePicker.FinishedPickingMedia -= OnImagePickerFinishedPickingMedia;
imagePicker.Canceled -= OnImagePickerCancelled;
}
}
}
Not forgetting to add permission in Info.plist :
<key>NSCameraUsageDescription</key>
<string>Use Camera</string>
In addition , iOS need to run in a physical device.
In Android , create the CameraPickerService :
[assembly: Dependency(typeof(CameraPickerService))]
namespace DependencyServiceDemos.Droid
{
public class CameraPickerService : ICameraPickerService
{
public Task<byte[]> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
// Start the camera (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
getImageByCamera,
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<byte[]>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
Adding permission in AndroidMainfest.xml :
<uses-permission android:name= "android.permission.CAMERA" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />
Get Image data in MainActivity :
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static MainActivity Instance { get; private set; }
public int CAMERA_JAVA_REQUEST_CODE = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Instance = this;
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
DependencyService.Register<ITextToSpeechService, TextToSpeechService>();
}
// Field, property, and method for Picture Picker
public static readonly int PickImageId = 1000;
public TaskCompletionSource<byte[]> PickImageTaskCompletionSource { set; get; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == PickImageId)
{
if ((resultCode == Result.Ok) && (intent != null))
{
Bundle bundle = intent.Extras;
Bitmap bitmap = (Bitmap)bundle.Get("data");
//// Set the Stream as the completion of the Task
MemoryStream memoryStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, memoryStream);
PickImageTaskCompletionSource.SetResult(memoryStream.ToArray());
}
else
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
Finally , show image in ContentPage of Forms :
async void OnPickPhotoButtonClicked(object sender, EventArgs e)
{
(sender as Button).IsEnabled = false;
byte[] data = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
MemoryStream stream = new MemoryStream(data);
if (stream != null)
{
image.Source = ImageSource.FromStream(() => stream) ;
}
(sender as Button).IsEnabled = true;
}
The effect :
Note : If want to pick a Photo from the Picture Library, you can have a look at this official document .

Xamarin.Forms Directory Picker

I would like to save a file in a user selected folder, thats why I would like to provide a directory list to user and user will be able to choose the directory where he wants to export the data. Unfortuntely I could not find any example for directory/folder picker, I just found a file picker which is not useful for me..
https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows
Is there any component for picking a folder for Xamarin.Forms? Actually I am just doing for Android but we use Xamarin.forms
There is none I can think of.
With netstandard everything is way more simple as you can use the classic c# File api to get the folders.
You just have to know the mappings between special folders and android folders (per example):
System.Environment.SpecialFolder Path
ApplicationData INTERNAL_STORAGE/.config
Desktop INTERNAL_STORAGE/Desktop
LocalApplicationData INTERNAL_STORAGE/.local/share
MyDocuments INTERNAL_STORAGE
MyMusic INTERNAL_STORAGE/Music
MyPictures INTERNAL_STORAGE/Pictures
MyVideos INTERNAL_STORAGE/Videos
Personal INTERNAL_STORAGE
source: https://learn.microsoft.com/en-US/xamarin/android/platform/files/
same for ios:
https://learn.microsoft.com/en-US/xamarin/ios/app-fundamentals/file-system
But it's really easy to implement, just enumerate all folders and display them in a ListView.
EDIT: more details on implementation.
In fact you want to code a "directory explorer", it's easy, here is the concept.
You have a ListView in your Page
You have a Cancel button and a Select button in your Page
You have a CurrentPath in your ViewModel
You bind CurrentPath to the Title of your Page
You have an List<DirectoryViewModel> Directories in your ViewModel
Each time a user click on a item from the list:
You add the directory name in your current path
You get all the directories from the new path, and update your Directories property (don't forget RaisePropertyChange(nameof(Directories)))
The ListView will be updated accordingly
Each time you back:
You remove last part of your current path
same as before
If you arrive to root path "/", you do nothing when clicking on back.
Oh and you could use this Grid component to instead of the ListView, will be nicer ;)
https://github.com/roubachof/Sharpnado.Presentation.Forms#grid-Layout
You can edit this to make it work..
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 Java.IO;
using Java.Util;
namespace Android.Basic.IO
{
public class DirectoryPicker : ListActivity
{
public const String START_DIR = "startDir";
public const String ONLY_DIRS = "onlyDirs";
public const String SHOW_HIDDEN = "showHidden";
public const String CHOSEN_DIRECTORY = "chosenDir";
public const int PICK_DIRECTORY = 43522;
private File dir;
private Boolean showHidden = false;
private bool onlyDirs = true;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
Bundle extras = Intent.Extras;
dir = OS.Environment.ExternalStorageDirectory;
if (extras != null)
{
String preferredStartDir = extras.GetString(START_DIR);
showHidden = extras.GetBoolean(SHOW_HIDDEN, false);
onlyDirs = extras.GetBoolean(ONLY_DIRS, true);
if (preferredStartDir != null)
{
File startDir = new File(preferredStartDir);
if (startDir.IsDirectory)
{
dir = startDir;
}
}
}
SetContentView(Resource.Layout.folder_chooser_activity);
var title = dir.AbsolutePath.ToString();
Title = (title);
Button btnChoose = (Button)FindViewById(Resource.Id.btnChoose);
String name = dir.Name;
if (name.Length == 0)
name = "/";
btnChoose.Text = ("Choose " + "'" + name + "'");
btnChoose.Click += delegate
{
returnDir(dir.AbsolutePath);
};
ListView lv = this.ListView;
lv.TextFilterEnabled = (true);
if (!dir.CanRead())
{
Context context = ApplicationContext;
String msg = "Could not read folder contents.";
Toast.MakeText(context, msg, ToastLength.Long).Show();
return;
}
var files = filter(dir.ListFiles(), onlyDirs, showHidden);
String[] names = Names(files);
ListAdapter = (new ArrayAdapter<String>(this, Resource.Layout.folder_chooser_item, names));
lv.ItemClick += (ff, gg) =>
{
var position = gg.Position;
if (!files[gg.Position].IsDirectory)
return;
String path = files[position].AbsolutePath;
var intent = new Intent(this, typeof(DirectoryPicker));
intent.PutExtra(DirectoryPicker.START_DIR, path);
intent.PutExtra(DirectoryPicker.SHOW_HIDDEN, showHidden);
intent.PutExtra(DirectoryPicker.ONLY_DIRS, onlyDirs);
StartActivityForResult(intent, PICK_DIRECTORY);
};
}
protected void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_DIRECTORY && resultCode == (int)Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
returnDir(path);
}
}
private void returnDir(String path)
{
Intent result = new Intent();
result.PutExtra(CHOSEN_DIRECTORY, path);
SetResult(Result.Ok, result);
Finish();
}
public List<File> filter(File[] file_list, bool onlyDirs, bool showHidden)
{
var files = new List<File>();
foreach (var file in file_list)
{
if (onlyDirs && !file.IsDirectory)
continue;
if (!showHidden && file.IsHidden)
continue;
files.Add(file);
}
Collections.Sort(files);
return files;
}
public String[] Names(List<File> files)
{
String[] names = new String[files.Count];
int i = 0;
foreach (var file in files)
{
names[i] = file.Name;
i++;
}
return names;
}
}
}
Start activity as result then catch in OnActivityResult
if (requestCode == DirectoryPicker.PICK_DIRECTORY && resultCode == Result.Ok)
{
Bundle extras = data.Extras;
String path = (String)extras.Get(DirectoryPicker.CHOSEN_DIRECTORY);
// do stuff with path
}

How to make phone calls using Xamairn forms?

I'm new in xamarin and I want make a phone call directly (without opening the dialler). I tried with this example but it doesn't work.
Click Please help
public class PhoneCall_Droid : IPhoneCall
{
public void MakeQuickCall(string PhoneNumber)
{
try
{
var uri = Android.Net.Uri.Parse(string.Format("tel:{0}", PhoneNumber));
var intent = new Intent(Intent.ActionCall, uri);
Xamarin.Forms.Forms.Context.StartActivity(intent);
}
catch (Exception ex)
{
new AlertDialog.Builder(Android.App.Application.Context).SetPositiveButton("OK", (sender, args) =>
{
//User pressed OK
})
.SetMessage(ex.ToString())
.SetTitle("Android Exception")
.Show();
}
}
}
there are two error in your code above:
1.Xamarin.Forms.Forms.Context could not get the correct context.
you could defined a static variable in MainActiviy like :
public static MainActivity Instance;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Instance = this;
LoadApplication(new App());
}
you also could use the Current Activity Plugin,you could refer to Current Activity
2.After Android6.0 you should requests the runtime permissions and the official doucument
here is a simple example:
[assembly: Xamarin.Forms.Dependency(typeof(PhoneCall_Droid))]
namespace App18.Droid
{
class PhoneCall_Droid: IPhoneCall
{
public void MakeQuickCall(string PhoneNumber)
{
try
{
if(ActivityCompat.CheckSelfPermission(MainActivity.Instance, Android.Manifest.Permission.CallPhone) != Android.Content.PM.Permission.Granted ){
ActivityCompat.RequestPermissions(MainActivity.Instance, new string[] {Android.Manifest.Permission.CallPhone }, 1);
return;
}
else
{
var uri = Android.Net.Uri.Parse(string.Format("tel:{0}", PhoneNumber));
var intent = new Intent(Intent.ActionCall, uri);
MainActivity.Instance.StartActivity(intent);
}
}
catch (Exception ex)
{
new AlertDialog.Builder(MainActivity.Instance).SetPositiveButton("OK", (sender, args) =>
{
//User pressed OK
})
.SetMessage(ex.ToString())
.SetTitle("Android Exception")
.Show();
}
}
}
}
and you also could to use the nugetpackage Plugin.Permissions to request runtime permissions(Permission.Location)
refer to Plugin.Permissions
finally you could call like
DependencyService.Get<IPhoneCall>().MakeQuickCall(phonenumber);

receive message from android beam in xamarin forms

I'm develop cross-platform mobile application that use NFC. I already check the xamarin android beam sample here. Now i'm trying implement the same sample using xamarin forms so i'm using dependency service to call the function from android project.
I already create Ndef message and send function:
using System;
using System.Text;
using Android.App;
using MyApp.Droid;
using Android.Nfc;
using Xamarin.Forms;
[assembly: Dependency(typeof(PhoneBeam))]
namespace MyApp.Droid
{
public class PhoneBeam : Activity, NfcAdapter.ICreateNdefMessageCallback, NfcAdapter.IOnNdefPushCompleteCallback, iBeam
{
private NfcAdapter nfcAdapter;
public void Beam()
{
nfcAdapter = NfcAdapter.GetDefaultAdapter(MainActivity.Instance);
nfcAdapter.SetNdefPushMessageCallback(this, MainActivity.Instance);
nfcAdapter.SetOnNdefPushCompleteCallback(this, MainActivity.Instance);
}
public NdefMessage CreateNdefMessage(NfcEvent evt)
{
DateTime time = DateTime.Now;
var text = ("Beam me up!\n\n" + "Beam : " +
time.ToString("HH:mm:ss"));
NdefMessage msg = new NdefMessage(
new NdefRecord[]{ CreateMimeRecord (
"application/com.companyname.MyApp",
Encoding.UTF8.GetBytes (text)) });
return msg;
}
public NdefRecord CreateMimeRecord(String mimeType, byte[] payload)
{
byte[] mimeBytes = Encoding.UTF8.GetBytes(mimeType);
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
return mimeRecord;
}
public void OnNdefPushComplete(NfcEvent e){}
}
}
However, I really don't know how to receive a message. In android beam sample, they implement it in mainactivity. Here's sample:
protected override void OnResume ()
{
base.OnResume ();
if (NfcAdapter.ActionNdefDiscovered == Intent.Action) {
ProcessIntent (Intent);
}
}
void ProcessIntent (Intent intent)
{
IParcelable [] rawMsgs = intent.GetParcelableArrayExtra (
NfcAdapter.ExtraNdefMessages);
NdefMessage msg = (NdefMessage) rawMsgs [0];
mInfoText.Text = Encoding.UTF8.GetString (msg.GetRecords () [0].GetPayload ());
}
So i want to implement in class file so i can use dependencyService. Is there a way to implement this?
Edit: I did the send function:
public NdefMessage CreateNdefMessage (NfcEvent evt)
{
DateTime time = DateTime.Now;
var text = ("Beam me up!\n\n" +
"Beam Time: " + time.ToString ("HH:mm:ss"));
NdefMessage msg = new NdefMessage (
new NdefRecord[] { CreateMimeRecord (
"application/com.companyname.MyApp", Encoding.UTF8.GetBytes (text))
});
return msg;
}
But it return as "NEW TAG COLLECTED: application/com.companyname.MyApp". I want to resume MyApp and show the message. But it didn't.

BackgroundTaskRegistration trigger property is null

Hi want to receive push notifications on background task for that i have created Portable library here is my Background task class
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Networking.PushNotifications;
using Windows.Storage;
using Windows.UI.Notifications;
namespace BackgroundTask
{
public sealed class NotificationTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Get the background task details
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
string taskName = taskInstance.Task.Name;
Debug.WriteLine("Background " + taskName + " starting...");
// Store the content received from the notification so it can be retrieved from the UI.
ToastNotification notification = (ToastNotification )taskInstance.TriggerDetails;
settings.Values[taskName] = notification.Content;
NotificationTask.AddTostNotification(notification.Content);
Debug.WriteLine("Background " + taskName + " completed!");
}
private static void AddTostNotification(String xmlDocument)
{
List<string> messageSection = NotificationTask.GetMessageAndLandingPage(xmlDocument, "toast");
if (messageSection == null) { return; }
ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(messageSection[0]));
// toastTextElements[1].AppendChild(toastXml.CreateTextNode(message));
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("launch", messageSection[1]);
XmlElement audio = toastXml.CreateElement("audio");
audio.SetAttribute("src", "ms-appx:///Assets/Play-Guitar.wav");
//audio.SetAttribute("loop", "true");
toastNode.AppendChild(audio);
//launch tost immediatly
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
Here i am registering Task
internal async void InitChannel()
{
// Applications must have lock screen privileges in order to receive raw notifications
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
// Make sure the user allowed privileges
if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified)
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
try
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (channel != null)
{
roamingSettings.Values["ExistingPushChannel"] = channel.Uri;
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
channel.PushNotificationReceived += OnPushNotificationReceived;
UnregisterBackgroundTask();
RegisterBackgroundTask();
}
else
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
catch
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
}
private void RegisterBackgroundTask()
{
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
PushNotificationTrigger trigger = new PushNotificationTrigger();
taskBuilder.SetTrigger(trigger);
// Background tasks must live in separate DLL, and be included in the package manifest
// Also, make sure that your main application project includes a reference to this DLL
taskBuilder.TaskEntryPoint = "BackgroundTask.NotificationTask";
taskBuilder.Name = "PlaypushNotification";
try
{
BackgroundTaskRegistration task = taskBuilder.Register();
task.Completed += BackgroundTaskCompleted;
}
catch
{
UnregisterBackgroundTask();
}
}
private bool UnregisterBackgroundTask()
{
foreach (var iter in BackgroundTaskRegistration.AllTasks)
{
IBackgroundTaskRegistration task = iter.Value;
if (task.Name == "PlaypushNotification")
{
task.Unregister(true);
return true;
}
}
return false;
}
In my Manifest file
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.NotificationTask">
<BackgroundTasks>
<Task Type="pushNotification" />
</BackgroundTasks>
</Extension>
</Extensions>
PushNotification Trigger is not firing, when i debug i found that trigger property of BackgroundTaskRegistration is null. what is the issue? What wrong is going here?

Resources