近日,使用Mono For Andriod开发手机项目,遇到上述难题,现总结解决方案如下:
using Android.App;
using Android.Content;
using Android.OS;
using Java.Lang;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace Vito.Phone.DataService
{
//[Service]绝对不能缺少,否则,无法进去Service
[Service]
public class EventService : Service
{
//点击查看
Intent messageIntent = null;
PendingIntent messagePendingIntent = null;
//通知栏消息
//private int messageNotificationID = 1000;
Notification messageNotification = null;
NotificationManager messageNotificatioManager = null;
System.Timers.Timer timer;
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 10000;//执行间隔时间,单位为毫秒
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer1_Elapsed);
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
timer.Stop();
base.OnDestroy();
}
private void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
messageNotification = new Notification();
messageNotification.Icon = Resource.Drawable.Icon;
messageNotification.TickerText = new Java.Lang.String("新事件");
messageNotification.Defaults = NotificationDefaults.Sound;
// 点击后自动清除Notification
messageNotification.Flags = NotificationFlags.AutoCancel;
messageNotificatioManager = this.GetSystemService(Service.NotificationService) as NotificationManager;
messageIntent = new Intent(this, typeof(Activity1));
messageIntent.SetAction(Intent.ActionMain);
messageIntent.AddCategory(Intent.CategoryLauncher);
messageIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ResetTaskIfNeeded);
//PendingIntentFlags.UpdateCurrent 记住关闭前的activity
messagePendingIntent = PendingIntent.GetActivity(this, 0, messageIntent, PendingIntentFlags.UpdateCurrent);
messageNotification.SetLatestEventInfo(this,
new Java.Lang.String("新事件"),
new Java.Lang.String("奥巴马宣布,本拉登兄弟挂了!"),
PendingIntent.GetActivity(this, 0, messageIntent, 0));
messageNotificatioManager.Notify(0, messageNotification);
}
}
}
在Activity中调用这个Service:StartService(new Intent(this, typeof(EventService)));