如何显示通知甚至应用程序未运行

时间:2014-05-23 19:03:45

标签: android

我在android.i中初学者创建一个服务,以便在mainActivity上的onCreat上显示通知时调用

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent a = new Intent(this,myService.class);
        startService(a);
    }

}

这是我的服务类

public class myService extends Service{
  private NotificationManager mManager;

 @Override
    public void onCreate() {

     mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

       Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
       notification.flags |= Notification.FLAG_AUTO_CANCEL;
       notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

       mManager.notify(0, notification);
 }

但我想如果我的应用程序没有运行我可以显示此服务,例如,如果我的手机时间大于9我只在一天中显示此通知。任何想法?提前谢谢

2 个答案:

答案 0 :(得分:6)

通知在后台运行,不需要运行应用程序。虽然应用程序没有运行,但通知也有效,这是他们的主要任务。我建议你使用Vogella的教程和文档:

http://www.vogella.com/tutorials/AndroidNotifications/article.html

http://developer.android.com/guide/topics/ui/notifiers/notifications.html

答案 1 :(得分:0)

  1. 您不希望在应用运行时显示通知。这只是烦人的,并且(通常)没有意义。当然有例外。

  2. 如果您想在特定时间显示通知,则应考虑使用AlarmManager

  3. 如果您想从服务器或其他任何地方触发通知,请使用Google Cloud Messaging

相关问题