How to use Broadcast Reciever in Xamarin.Form reference to this forum http://forums.xamarin.com/discussion/7070/how-to-prevent-sms-going-to-inbox
the class
public class SmsReceiver : BroadcastReceiver
{
public static readonly string IntentAction = "android.provider.Telephony.SMS_RECEIVED";
public override void OnReceive(Context context, Intent intent)
{
InvokeAbortBroadcast();
try
{
if (intent.Action != IntentAction) return;
var bundle = intent.Extras;
if (bundle == null) return;
var pdus = bundle.Get("pdus");
var castedPdus = JNIEnv.GetArray<Java.Lang.Object>(pdus.Handle);
var msgs = new SmsMessage[castedPdus.Length];
var sb = new StringBuilder();
String sender = null;
for (var i = 0; i < msgs.Length; i++)
{
var bytes = new byte[JNIEnv.GetArrayLength(castedPdus[i].Handle)];
JNIEnv.CopyArray(castedPdus[i].Handle, bytes);
msgs[i] = SmsMessage.CreateFromPdu(bytes);
if (sender == null) sender = msgs[i].OriginatingAddress;
sb.Append(string.Format("SMS From: {0}{1}Body: {2}{1}", msgs[i].OriginatingAddress,
System.Environment.NewLine, msgs[i].MessageBody));
}
if (sender != null && sender.EndsWith("09068100820"))
{
// Process our sms...
// SMS.updateMessageBox("\nFrom: " + msg.getOriginatingAddress() + "\n" +
//"Message: " + msg.getMessageBody() + "\n");
/*((SMS) context).delete();*/
Toast.MakeText(context, "IsOrderedBroadcast :" + IsOrderedBroadcast.ToString() + "\n" + sb.ToString(), ToastLength.Long).Show();
}
else
{
ClearAbortBroadcast();
}
}
catch (Exception ex)
{
Toast.MakeText(context, ex.Message, ToastLength.Long).Show();
}
}
}
How to implement this class in Xamarin.Form and get the incoming SMS, Thanks in advance and Good Day :D
From Android 4.4, You can't do any kind of operation on SMS except just reading it if your app isn't the default SMS app.
If your app is default sms app and you want to block sender or whatever then put your SmsReceiver in Android Project and register it in Application class.
I don't think you need to do anything in Forms Project.
Related
So I am pretty new to Xamarin.Android, I have managed to connect to my Bluetooth printer device using the code below, so now I want to send a print command to the printer but I have not been able to for several weeks now. Searched the internet but I have not been able to find a solution. Any assistance will be greatly appreciated
Button btnConnect;
TextView txtView;
Button btnPrint;
BluetoothSocket socket;
BluetoothAdapter adapter;
BluetoothDevice bluetoothDevice;
private byte[] buffer;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.BrianPeek);
FindViews();
HandleEvents();
buffer = new byte[1024];
}
private void HandleEvents()
{
btnConnect.Click += BtnConnect_Click;
btnPrint.Click += Print_Click;
}
private void Print_Click(object sender, EventArgs e)
{
// Variables
string ipAddress = "192.168.1.100";
int portNumber = 9100;
List<string> myText = new List<string>() { "Line1", "Line2" };
// Try to find the platform specific services
// var printer = DependencyService.Get<DSInterfaces.IPrinter>();
var printer = new Printer();
if (printer == null) {
// Do not proceed if no services found for the platform
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Printer");
alert.SetMessage("Error");
alert.Show();
}
try
{
// Call themethod, declare by the IPrinter interface
printer.Print(ipAddress, portNumber, myText);
}
catch (Exception ex)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Printer");
alert.SetMessage("Failed to print redemption slip\nReason "+ex.Message);
alert.Show();
// Exception here could mean difficulties in connecting to the printer etc
//await DisplayAlert("Error", $"Failed to print redemption slip\nReason: {ex.Message}", "OK");
}
}
private async void BtnConnect_Click(object sender, EventArgs e)
{
adapter = BluetoothAdapter.DefaultAdapter;
if(adapter == null) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("No Bluetooth Adapter Found");
alert.Show();
}
if (!adapter.IsEnabled) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("Bluetooth Adapter is not set!");
alert.Show();
}
bluetoothDevice = (from bd in adapter.BondedDevices
where bd.Name == "MTP-II"
select bd).FirstOrDefault();
if (bluetoothDevice != null) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("Bluetooth device " + bluetoothDevice.Name );
alert.Show();
//Connect Bluetooth Device
socket = bluetoothDevice.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
await socket.ConnectAsync();
//after connection, communication occurs through input and output stream
// Read data from the device
await socket.InputStream.ReadAsync(buffer, 0, buffer.Length);
// Write data to the device
await socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.SetTitle("Bluetooth");
alert.SetMessage("The device is not found");
alert.Show();
}
}
private void FindViews()
{
btnConnect = FindViewById<Button>(Resource.Id.btnConnectBlue);
txtView = FindViewById<TextView>(Resource.Id.txtText);
btnPrint = FindViewById<Button>(Resource.Id.btnConnectPrint);
}
I am trying to implement media/rich/enhanced notifications in ios. I have an iPhone 6, 6s and 7. The image I send in the payload appears in the rich notification on the 6 , but not on the 6s or 7. The code seems to just stop at the CreateDownloadTask (I have verified that I can change the Body text just before that line of code, but I can’t after). I have even had simpler version of this use NSData.FromUrl(url) but the code “breaks” at that line. The odd think is that it doesn’t truly break, it displays the text for the Body element that was originally pushed. Even a try catch doesn’t grab the error. FYI..category is there for the custom ui I am building. Can't figure out why it only works properly on iphone 6 (all the phone are on 10.2.x or above)
the payload is {"aps":{"alert":{"title":"title", "subtitle":"subtitle","body":"body"}, "category":"pushWithImage","mutable-content":1}, "pushImage":"https://ewcweb.azurewebsites.net/media/boldlythumb.png"}
I can’t send project but below is the service extension code:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Foundation;
using SDWebImage;
using UIKit;
using UserNotifications;
namespace notifications
{
[Register ("NotificationService")]
public class NotificationService : UNNotificationServiceExtension
{
UNMutableNotificationContent BestAttemptContent { get; set; }
public Action ContentHandler { get; set; }
const string ATTACHMENT_IMAGE_KEY = "pushImage";
const string ATTACHMENT_FILE_NAME = "-attachment-image.";
protected NotificationService (IntPtr handle) : base (handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public async Task<byte[]> LoadImage (string imageUrl)
{
var httpClient = new HttpClient ();
var contentsTask = await httpClient.GetByteArrayAsync (imageUrl);
return contentsTask;
}
public override void DidReceiveNotificationRequest (UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
string imageURL = null;
ContentHandler = contentHandler;
BestAttemptContent = request.Content.MutableCopy () as UNMutableNotificationContent;
if (BestAttemptContent != null) {
if (BestAttemptContent.UserInfo.ContainsKey (new NSString (ATTACHMENT_IMAGE_KEY))) {
imageURL = BestAttemptContent.UserInfo.ValueForKey (new NSString (ATTACHMENT_IMAGE_KEY)).ToString ();
}
if (imageURL == null) {
ContentHandler (BestAttemptContent);
return;
}
var url = new NSUrl (imageURL.ToString ());
NSError err = null;
var task = NSUrlSession.SharedSession.CreateDownloadTask ( new NSMutableUrlRequest (url),(tempfile, response, error) => {
if (error != null)
{
ContentHandler (BestAttemptContent);
return;
}
if (tempfile == null)
{
ContentHandler (BestAttemptContent);
return;
}
var cache = NSSearchPath.GetDirectories (NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User, true);
var cachesFolder = cache [0];
var guid = NSProcessInfo.ProcessInfo.GloballyUniqueString;
var fileName = guid + ".png";
var cacheFile = cachesFolder + "/" + fileName;
var attachmentURL = NSUrl.CreateFileUrl (cacheFile, false, null);
NSFileManager.DefaultManager.Move(tempfile, attachmentURL, out err);
if (err != null)
{
ContentHandler (BestAttemptContent);
return;
}
// Create attachment;
var attachmentID = "image";
var options = new UNNotificationAttachmentOptions ();
var attachment = UNNotificationAttachment.FromIdentifier (attachmentID, attachmentURL, options, out err);
BestAttemptContent.Attachments = new UNNotificationAttachment [] { attachment };
BestAttemptContent.Title = BestAttemptContent.Title;
BestAttemptContent.Body = BestAttemptContent.Body;
BestAttemptContent.CategoryIdentifier = BestAttemptContent.CategoryIdentifier;
BestAttemptContent.Subtitle = BestAttemptContent.Subtitle;
//Display notification
ContentHandler (BestAttemptContent);
});
task.Resume ();
} else {
// Display notification
ContentHandler (BestAttemptContent);
}
}
public override void TimeWillExpire ()
{
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
ContentHandler (BestAttemptContent);
}
}
}
I'm writting sms application, which get from server by restapi number and message where to send and also receive sms from receipent. I have issue when received sms has more than 160 characters. And issue is when I have more than 160 characters to send by SMS.
Receive sms code:
public override void OnReceive(Context context, Intent intent)
{
if (intent.HasExtra("pdus"))
{
var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
foreach(var item in smsArray)
{
var sms = SmsMessage.CreateFromPdu((byte[])item);
SendReceivedStatus(sms.OriginatingAddress, sms.MessageBody);
}
}
}
SendReceivedStatus(sms.OriginatingAddress, sms.MessageBody);
It's a my method that convert to json receipentNumber and message.
Now my send sms code:
var sent = PendingIntent.GetBroadcast(Application.Context, 0, new Intent("SMS_SENT"), 0);
SmsManager.Default.SendTextMessage(responseModel.receipent, null, responseModel.message, sent, null);
protected override void OnResume()
{
base.OnResume();
var smsSentReceiver = new SMSSentReceiver();
RegisterReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
}
public override void OnReceive(Context context, Intent intent)
{
switch ((int)ResultCode)
{
case (int)Result.Ok:
SenderActivity.resultsms = true;
SendStatus();
break;
case (int)SmsResultError.GenericFailure:
SenderActivity.resultsms = false;
SendStatus();
break;
case (int)SmsResultError.NoService:
SenderActivity.resultsms = false;
SendStatus();
break;
case (int)SmsResultError.NullPdu:
SenderActivity.resultsms = false;
SendStatus();
break;
case (int)SmsResultError.RadioOff:
SenderActivity.resultsms = false;
SendStatus();
break;
}
}
How to pack these messages?
Since SmsMessage.CreateFromPdu((byte[])) is deprecated since Android API level 19, here I also provide method to receive message more than 160 characters after KitKat version, here is my demo:
[BroadcastReceiver(Enabled = true, Label = "SMS Receiver")]
[IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SMSReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Bundle bundle = intent.Extras;
if (bundle != null)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
SmsMessage[] msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
var smstext = new StringBuilder();
foreach (var msg in msgs)
{
smstext.Append(msg.DisplayMessageBody.ToString());
}
Console.WriteLine(smstext.ToString());//output the received sms
}
else
{
var smsArray = (Java.Lang.Object[])bundle.Get("pdus");
SmsMessage[] messages = new SmsMessage[smsArray.Length];
for (int i = 0; i < smsArray.Length; i++)
{
messages[i] = SmsMessage.CreateFromPdu((byte[])smsArray[i]);
}
StringBuilder content = new StringBuilder();
if (messages.Length > 0)
{
foreach (var message in messages)
{
content.Append(message.DisplayMessageBody.ToString());
}
}
Console.WriteLine(content.ToString());//output the received sms
}
}
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
}
}
I've tested my demo on Android 6.0 device and it works fine, I now can't find a Android 4.0 device for testing, but I think the method should work here. Any problem about this issue, please leave a comment.
This is driving me crazy. I wrote a code quite a while ago that was working, and opened it again and it happens that I am not able to transfer my assets from the mobile to the wearable device.
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
// convert asset into a file descriptor and block until it's ready
Log.d(TAG, "api client" + mApiClient);
DataApi.GetFdForAssetResult result = Wearable.DataApi.getFdForAsset(mApiClient, asset).await();
if (result == null) {
Log.w(TAG, "getFdForAsset returned null");
return null;
}
if (result.getStatus().isSuccess()) {
Log.d(TAG, "success");
} else {
Log.d(TAG, result.getStatus().getStatusCode() + ":" + result.getStatus().getStatusMessage());
}
InputStream assetInputStream = result.getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
And this is the code from which I call the loadBitmapFrom Asset method.
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
ArrayList<DataMap> dataMaps = dataMap.getDataMapArrayList("dataMaps");
ArrayList<String> names = new ArrayList<>();
ArrayList<String> permalinks = new ArrayList<>();
ArrayList<Asset> images = new ArrayList<>();
for (int i = 0 ; i < dataMaps.size() ; i++) {
Log.d(TAG, dataMaps.get(i).getString("name"));
names.add(dataMaps.get(i).getString("name"));
permalinks.add(dataMaps.get(i).getString("permalink"));
images.add(dataMaps.get(i).getAsset("image"));
}
editor.putInt("my_selection_size", names.size());
for (int i=0; i <names.size() ; i++) {
editor.putString("my_selection_name_" + i, names.get(i));
editor.putString("my_selection_permalink_" + i, permalinks.get(i));
Log.d(TAG, "asset number " + i + " " + images.get(i));
Bitmap bitmap = loadBitmapFromAsset(images.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
editor.putString("my_selection_image_" + i, encoded);
}
And on the mobile side :
private void sendData(PutDataMapRequest dataMap) {
PutDataRequest request = dataMap.asPutDataRequest();
request.setUrgent();
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mApiClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
com.orange.radio.horizon.tools.Log.d(TAG, "api client : " + mApiClient);
if (dataItemResult.getStatus().isSuccess()) {
com.orange.radio.horizon.tools.Log.d(TAG, "message successfully sent");
} else if (dataItemResult.getStatus().isInterrupted()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (interrupted)");
} else if (dataItemResult.getStatus().isCanceled()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (canceled)");
}
}
});
Log.d(TAG, "Sending data to android wear");
}
class ConfigTask extends AsyncTask<String, Void, String> {
ArrayList<WatchData> mitems;
int mType;
public ConfigTask(ArrayList<WatchData> items, int type)
{
mitems = items;
mType = type;
}
protected String doInBackground(String... str)
{
DataMap dataMap;
ArrayList<DataMap> dataMaps = new ArrayList<>();
Bitmap bitmap = null;
for (int i = 0 ; i < mitems.size() ; i++) {
dataMap = new DataMap();
URL url = null;
try {
url = new URL(mitems.get(i).mUrlSmallLogo);
Log.d(TAG, "url : " + url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Asset asset = createAssetFromBitmap(bitmap);
dataMap.putAsset("image", asset);
dataMap.putString("name", mitems.get(i).mName);
dataMap.putString("permalink", mitems.get(i).mPermalink);
dataMaps.add(dataMap);
}
PutDataMapRequest request = null;
switch (mType) {
case 0 :
request = PutDataMapRequest.create(SELECTION_PATH);
break;
case 1 :
request = PutDataMapRequest.create(RADIOS_PATH);
break;
case 2 :
request = PutDataMapRequest.create(PODCASTS_PATH);
break;
}
request.getDataMap().putDataMapArrayList("dataMaps", dataMaps);
request.getDataMap().putString("", "" + System.currentTimeMillis()); //random data to refresh
Log.d(TAG, "last bitmap : " + bitmap);
Log.d(TAG, "===============================SENDING THE DATAMAP ARRAYLIST==================================");
sendData(request);
return "h";
}
protected void onPostExecute(String name)
{
}
}
When executing that code, I see the following error happening :
02-02 14:47:59.586 7585-7601/? D/WearMessageListenerService﹕ 4005:ASSET_UNAVAILABLE
I saw that related thread Why does Wearable.DataApi.getFdForAsset produce a result with status 4005 (Asset Unavailable)? but it didn't really help me
I recently had the same problem... I solved it by updating the Google play service, and adding the same signing configuration to both the app and the wearable module. If it doesn't work on the first build go to "invalidate caches / restart" in files and it should work.
We have developed a Android App using Xamarin and we are facing problem in Azure Notification Hub. We were trying to send push notifications to Android devices registered in our Azure Mobile Service and no registered android devices are receiving the notifications. When we tried to debug it via Notification Hub in Azure Portal, the results are showing that the notifications are sent to the devices. However, the devices are not receiving the notifications which was receiving before.
Kindly let us know either we are missing something in our code (Find the code below) or is there any problem in Azure Notification Hub (for Android GCM).
Note: All the android permissions for push notifications are given in the same code file below and not in the Android manifest.
Our GCM Service Code Below:
using System.Text;
using Android.App;
using Android.Content;
using Android.Util;
using Gcm.Client;
//VERY VERY VERY IMPORTANT NOTE!!!!
// Your package name MUST NOT start with an uppercase letter.
// Android does not allow permissions to start with an upper case letter
// If it does you will get a very cryptic error in logcat and it will not be obvious why you are crying!
// So please, for the love of all that is kind on this earth, use a LOWERCASE first letter in your Package Name!!!!
using ByteSmith.WindowsAzure.Messaging;
using System.Diagnostics;
using System.Collections.Generic;
using System;
[assembly: Permission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "#PACKAGE_NAME#.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is only needed for android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace seeMuscatAndroidApp
{
//You must subclass this!
[BroadcastReceiver(Permission= Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "#PACKAGE_NAME#" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "#PACKAGE_NAME#" })]
public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase<GcmService>
{
public static string[] SENDER_IDS = new string[] { Constants.SenderID };
public const string TAG = "GoogleCloudMessaging";
}
[Service] //Must use the service tag
public class GcmService : GcmServiceBase
{
public static string RegistrationID { get; private set; }
private NotificationHub Hub { get; set; }
Context _generalContext;
public GcmService() : base(PushHandlerBroadcastReceiver.SENDER_IDS)
{
Log.Info(PushHandlerBroadcastReceiver.TAG, "GcmService() constructor");
}
protected override async void OnRegistered (Context context, string registrationId)
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
RegistrationID = registrationId;
_generalContext = context;
//createNotification("GcmService Registered...", "The device has been Registered, Tap to View!");
Hub = new NotificationHub(Constants.NotificationHubPath, Constants.ConnectionString);
try
{
await Hub.UnregisterAllAsync(registrationId);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debugger.Break();
}
var tags = new List<string>() { main.userCountry, main.userCity, main.userLatitude, main.userLongitude, main.userPhoneMake, main.userPhoneModel, main.userPhoneName, main.userPhoneAndroidVersion, main.userAppVersion,main.userUID};
Console.WriteLine("///////////HUB TAGS///////////////////");
Console.WriteLine("Country:" + main.userCountry);
Console.WriteLine("City:" + main.userCity);
Console.WriteLine("Latitude:" + main.userLatitude);
Console.WriteLine("Longitude:"+main.userLongitude);
Console.WriteLine("Make:" + main.userPhoneMake);
Console.WriteLine("Model:" + main.userPhoneModel);
Console.WriteLine("Phone Name:" + main.userPhoneName);
Console.WriteLine("Android Version:" + main.userPhoneAndroidVersion);
Console.WriteLine("App version:" + main.userAppVersion);
Console.WriteLine("User ID:" + main.userUID);
Console.WriteLine("///////////END OF HUB TAGS///////////////////");
try
{
var hubRegistration = await Hub.RegisterNativeAsync(registrationId, tags);
Debug.WriteLine("RegistrationId:" + hubRegistration.RegistrationId);
}
catch (Exception ex)
{
Debug.WriteLine("#########$$$$Error:"+ex.Message);
}
}
protected override void OnUnRegistered (Context context, string registrationId)
{
Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId);
//Remove from the web service
// var wc = new WebClient();
// var result = wc.UploadString("http://your.server.com/api/unregister/", "POST",
// "{ 'registrationId' : '" + lastRegistrationId + "' }");
//createNotification("GcmService Unregistered...", "The device has been unregistered, Tap to View!");
}
protected override void OnMessage (Context context, Intent intent)
{
Log.Info(PushHandlerBroadcastReceiver.TAG, "GCM Message Received!");
Debug.WriteLine("/********* GCM Received ****************");
var msg = new StringBuilder();
if (intent != null && intent.Extras != null)
{
foreach (var key in intent.Extras.KeySet())
msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
}
//Store the message
var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private);
var edit = prefs.Edit();
edit.PutString("last_msg", msg.ToString());
edit.Commit();
string message = intent.Extras.GetString("message");
if (!string.IsNullOrEmpty(message))
{
createNotification("New todo item!", "Todo item: " + message);
return;
}
string msg2 = intent.Extras.GetString("msg");
string notititle = intent.Extras.GetString("notititle");
if (!string.IsNullOrEmpty(msg2))
{
createNotification(notititle, msg2);
return;
}
// createNotification("PushSharp-GCM Msg Rec'd", "Message Received for C2DM-Sharp... Tap to View!");
//createNotification("Unknown message details", msg.ToString());
}
protected override bool OnRecoverableError (Context context, string errorId)
{
Log.Warn(PushHandlerBroadcastReceiver.TAG, "Recoverable Error: " + errorId);
return base.OnRecoverableError (context, errorId);
}
protected override void OnError (Context context, string errorId)
{
Log.Error(PushHandlerBroadcastReceiver.TAG, "GCM Error: " + errorId);
}
void createNotification(string title, string desc)
{
//Create notification
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
//Create an intent to show ui
Intent uiIntent = new Intent();
uiIntent.SetClass(this, typeof(dealsview));
uiIntent.PutExtra("contentID", "todaydeals");
uiIntent.PutExtra("contentName", "");
uiIntent.PutExtra("isSale", "");
//Create the notification
var notification = new Notification(Resource.Drawable.Icon, title);
//Auto cancel will remove the notification once the user touches it
notification.Flags = NotificationFlags.AutoCancel;
notification.Defaults = NotificationDefaults.All;
//Set the notification info
//we use the pending intent, passing our ui intent over which will get called
//when the notification is tapped.
notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));
//Show the notification
notificationManager.Notify(1, notification);
}
}
}
Permission are tags in the Manifest file that has XML data. While compiling DVM checks the Manifest file for permissions and other necessary data to package in the .apk. You should always follow the same format.
Please have a look at this tutorial for more information.