Начать уведомление как:
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" />
Я лично отформатировал бы его в двух частях: non-am/pm часть и/пополудни расстаются с ToLower:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
item.PostedOn.ToString("tt").ToLower();
Другая опция (который я исследую через секунду) состоит в том, чтобы захватить текущий DateTimeFormatInfo, создать копию и установить,/пополудни указатели к версии нижнего регистра. Затем используйте ту информацию о формате для нормального форматирования. Вы хотели бы кэшировать DateTimeFormatInfo, очевидно...
РЕДАКТИРОВАНИЕ: Несмотря на мой комментарий, я записал кэширующийся бит так или иначе. Это, вероятно, не будет быстрее , чем код выше (поскольку это включает блокировку и поиск по словарю), но это действительно делает код вызова более простым:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
Вот полная программа для демонстрации:
using System;
using System.Collections.Generic;
using System.Globalization;
public class Test
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
}
private static readonly Dictionary<DateTimeFormatInfo,DateTimeFormatInfo> cache =
new Dictionary<DateTimeFormatInfo,DateTimeFormatInfo>();
private static object cacheLock = new object();
public static DateTimeFormatInfo GetLowerCaseInfo()
{
DateTimeFormatInfo current = CultureInfo.CurrentCulture.DateTimeFormat;
lock (cacheLock)
{
DateTimeFormatInfo ret;
if (!cache.TryGetValue(current, out ret))
{
ret = (DateTimeFormatInfo) current.Clone();
ret.AMDesignator = ret.AMDesignator.ToLower();
ret.PMDesignator = ret.PMDesignator.ToLower();
cache[current] = ret;
}
return ret;
}
}
}
Вы могли разделить строку формата на две части, и затем нижний регистр/PM часть, как так:
DateTime now = DateTime.Now;
string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mm");
nowString = nowString + now.ToString("tt").ToLower();
Однако я думаю, что более изящное решение состоит в том, чтобы использовать DateTimeFormatInfo
экземпляр , что Вы создаете и заменяете AMDesignator
и PMDesignator
, свойства с и "пополудни" соответственно:
DateTimeFormatInfo fi = new DateTimeFormatInfo();
fi.AMDesignator = "am";
fi.PMDesignator = "pm";
string nowString = now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt", fi);
можно использовать DateTimeFormatInfo
экземпляр для настройки многих других аспектов преобразования DateTime
к string
.
РЕДАКТИРОВАНИЕ : пример Jon намного лучше, хотя я думаю, что дополнительный метод является все еще способом пойти так, Вы не должны повторять код везде. Я удалил замену и заменил первым примером Jon на месте в дополнительном методе. Мои приложения обычно являются приложениями интранет, и я не должен волноваться о неамериканских культурах.
Добавляют дополнительный метод, чтобы сделать это для Вас.
public static class DateTimeExtensions
{
public static string MyDateFormat( this DateTime dateTime )
{
return dateTime.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
dateTime.ToString("tt").ToLower();
}
}
...
item.PostedOn.MyDateFormat();
РЕДАКТИРОВАНИЕ : Другие идеи о том, как сделать это в , Как отформатировать DateTime как " 10 октября 2008 10:43 CST" в C#.