【问题标题】:Stay foreground using notification , How?使用通知保持前台,如何?
【发布时间】:2014-10-01 10:34:30
【问题描述】:

从文档中我了解到,当我们打开 another_one 时,我们的程序会进入后台,然后过一段时间,android 会调用 onDestroy() 来收回它的资源;但是我们的程序是一种观察者(假设我们有一个在后台播放音乐的 mediaplyer),它不应该在 int programState == 1 之前关闭(有一个电源按钮可以结束播放器或观察者)。此外,我了解到我们可以通过“通知”保持前台,这非常酷(但我不知道如何)!这是一个通知代码:

 in  Activity's onCreate(){

       //> reading some data and define some initial values .


       mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

       Notification app_notfiy =addNotification();

       //> still should perform somehing ?!?



}



   private Notification addNotification() {



   NotificationCompat.Builder builder =  
           new NotificationCompat.Builder(this)  
           .setSmallIcon(R.drawable.ic_launcher_new)  
           .setContentTitle(getText(string.app_name))  
           .setContentText("> This is a notification !?")
           .setUsesChronometer(true)
           ;  

   Intent notificationIntent = new Intent(this, MainActivity.class);  
   PendingIntent contentIntent = PendingIntent.getActivity(this, 0,      notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);  
   builder.setContentIntent(contentIntent);  


   return builder.build() ;

  }  

但是这里我们有两个问题。首先,我不认为通知真的附加到活动(也许它需要一些权限或使用服务不确定!?)!接下来我希望通知恢复应用程序而不是重新启动它!? (我认为它从 onCreate() 开始活动)如何强制它回到我们原来的位置?

我搜索了很多,但仍然找不到关于这个的好答案。任何想法 ?

【问题讨论】:

标签: java android service notifications foreground


【解决方案1】:

要实现这一点,您必须使用Service。看看this tutorial

您可以将该服务作为“前台服务”启动,该服务在后台运行,几乎不会被系统杀死。

为此,请致电startForeground(id, notification)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2017-10-27
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多