2010-03-08 258 views
2

在我的应用程序后台服务启动,并从该服务,我想设置状态栏通知,该服务已经启动下面是代码:处理状态栏通知

Context context = getApplicationContext(); 
    String ns = Context.NOTIFICATION_SERVICE; 
    int icon = R.drawable.icon; 
    CharSequence tickerText = "Hello"; 
    long when = System.currentTimeMillis(); 
    Notification notification = new Notification(icon, tickerText, when); 
    CharSequence contentTitle = "My notification"; 
    CharSequence contentText = "Hello World!"; 
    Intent notificationIntent = new Intent(MyService.this, MyClass.class); 
    notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK); 

    PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0); 

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
    mNotificationManager.notify(1, notification); 

通知显示在状态栏,但我只点击那个MyClass.class没有被解雇。并且在日志猫中它显示 “输入管理器服务窗口已经集中忽略了焦点...”

因此PLZ提供了解决方案。

在此先感谢

回答

2

我不知道你所说的“MyClass.class不解雇”的意思,但如果它已经加载和你希望的onCreate被称为再次,你可以期待错误的结果。我做的非常相似,让代码从通知触摸我已经运行活动的派生类执行的东西,我通过PendingIntent.FLAG_UPDATE_CURRENT作为第四个参数的构造函数的PendingIntent

PendingIntent contentIntent = PendingIntent.getActivity(YourService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

,我把我的代码执行的活动如下方法:

@Override 
public void onNewIntent(Intent intent) 
{ 
    super.onNewIntent(intent); 

    // your code here 

} 
+2

'FLAG_UPDATE_CURRENT'只影响其他'PendingIntents'。 'onNewIntent()',虽然是很重要的 - 如果该活动已经在运行,它不会收到'的onCreate()',因为它已经被创建。 – CommonsWare 2010-03-08 15:16:52

1

首先,不要使用getApplicationContext()。你ServiceContext,以及“应用程序上下文”一般是无用的地方,你需要一个Context

其次,我怀疑你需要FLAG_ACTIVITY_NEW_TASK

Here is a sample application表示使用Notifications。注册为类似`Intents`(例如,同样的动作,同样的部件)