Нажмите кнопку прослушивания уведомления [дубликат]

В ситуациях, когда у вас есть поток XML, содержащий один из нескольких возможных типов документов, вы можете построить XmlSerializer для каждого типа и вызвать XmlSerializer.CanDeserialize(XmlReader) , чтобы последовательно проверить, можно ли десериализовать документ в этот тип. Этот метод не продвигает XmlReader мимо корневого элемента, поэтому его можно вызвать несколько раз, не перечитывая поток.

Например, вы можете ввести следующий метод расширения:

public static partial class XmlSerializerExtensions
{
    public static object DeserializePolymorphicXml(this string xml, params Type[] types)
    {
        using (var textReader = new StringReader(xml))
        {
            return textReader.DeserializePolymorphicXml(types);
        }
    }

    public static object DeserializePolymorphicXml(this TextReader textReader, params Type[] types)
    {
        if (textReader == null || types == null)
            throw new ArgumentNullException();
        var settings = new XmlReaderSettings { CloseInput = false }; // Let caller close the input.
        using (var xmlReader = XmlReader.Create(textReader, settings))
        {
            foreach (var type in types)
            {
                var serializer = new XmlSerializer(type);
                if (serializer.CanDeserialize(xmlReader))
                    return serializer.Deserialize(xmlReader);
            }
        }
        throw new XmlException("Invalid root type.");
    }
}

Затем используйте его следующим образом:

var xmlBody = result.ResponseBody.DeserializePolymorphicXml(typeof(SuccessResponse), typeof(FailResponse));
if (xmlBody is SuccessResponse)
{
    // Handle successful response
}
else if (xmlBody is FailResponse)
{
    // Handle failed response
}
else
{
    // unknown response
    throw new InvalidOperationException("unknown response");
}

Пример скрипт .

25
задан Syed Raza Mehdi 10 June 2015 в 05:05
поделиться

1 ответ

Начать уведомление как:

private void startNotification(){
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager notificationManager = 
            (NotificationManager) getSystemService(ns);

    Notification notification = new Notification(R.drawable.ic_launcher, null, 
            System.currentTimeMillis());

    RemoteViews notificationView = new RemoteViews(getPackageName(),
            R.layout.mynotification);

    //the intent that is started when the notification is clicked (works)
    Intent notificationIntent = new Intent(this, FlashLight.class);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, 
            notificationIntent, 0);

    notification.contentView = notificationView;
    notification.contentIntent = pendingNotificationIntent;
    notification.flags |= Notification.FLAG_NO_CLEAR;

    //this is the intent that is supposed to be called when the 
    //button is clicked
    Intent switchIntent = new Intent(this, switchButtonListener.class);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, 
            switchIntent, 0);

    notificationView.setOnClickPendingIntent(R.id.closeOnFlash, 
            pendingSwitchIntent);

    notificationManager.notify(1, notification);
}


public static class switchButtonListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("Here", "I am here");
        FlashOnOff flashLight;
        flashLight = new FlashOnOff();
        flashLight.flashLightOff();
        flashLight.releaseCamera();         
    }
}

xml used:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="100" >

<ImageView
    android:id="@+id/notifiation_image"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="30"
    android:contentDescription="@string/appImage"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/appName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="50"
    android:gravity="center"
    android:text="@string/flashLightOn"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/closeOnFlash"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="20"
    android:text="@string/close" />

В манифесте под тегом приложения:

<receiver android:name="FlashLight$switchButtonListener" />
45
ответ дан shyam 22 August 2018 в 07:29
поделиться
  • 1
    @PoojaShah рад помочь :) – Syed Raza Mehdi 19 May 2015 в 13:28
  • 2
    Как работает декларация в манифесте? Является ли FlashLight вашим классом, содержащим swiftButtonListener? Это имя приложения? – Shaik MD Ashiq 18 July 2015 в 15:43
  • 3
    название его деятельности – Syed Raza Mehdi 18 July 2015 в 16:37
  • 4
    Это действительно отличная идея! Спасибо, что поделились ею! – Mohammad 3 December 2015 в 15:15
  • 5
    @Bunny вы регистрируете приемник в манифесте? – Syed Raza Mehdi 1 April 2016 в 18:42
Другие вопросы по тегам:

Похожие вопросы: