2017-01-30 17 views
2

我试图在使用广播接收器和计时器显示的间隔中显示通知。它在应用程序运行时工作,但在应用程序被终止时无法工作。Android广播接收器在应用程序中断时不工作

接收机看起来像

public class MyReceiver extends BroadcastReceiver { 
    int j; 
     public void onReceive(final Context context, Intent intent) { 

     // Vibrate the mobile phone 
     //Declare the timer 
     Timer t = new Timer(); 

//Set the schedule function and rate 
     t.schedule(new TimerTask() { 

         @Override 
         public void run() { 
          Log.d("ME", "Notification started"); 

          NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); 
          mBuilder.setSmallIcon(R.drawable.ddc); 
          mBuilder.setContentTitle("My notification"); 
          mBuilder.setDefaults(Notification.DEFAULT_SOUND); 
          mBuilder.setContentText("Hello World!"); 

          NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
          mNotificationManager.notify(j++, mBuilder.build()); 

         } 

        }, 
       0, 
       30000); 
    } 
} 

的AndroidManifest.xml貌似

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.background.pushnotification"> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme.NoActionBar"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <receiver android:name="MyReceiver" 
      android:enabled="true" 
      android:exported="true" 
      > 
      <intent-filter> 
       <action android:name="com.background.myreceiver" /> 
       <action android:name="android.intent.action.PHONE_STATE" /> 
      </intent-filter> 
     </receiver> 
    </application> 

</manifest> 

它应用程序正在运行时的间隔中仅显示通知。它在应用程序被杀时不显示通知。我错过了什么?

+0

也许您需要添加WAKE_LOCK权限? –

+1

请更具体地说明“当应用程序被杀时”的含义。 – Karakuri

+0

从后台关闭应用程序。通知未收到 –

回答

2

“当应用程序被杀害”不是一个确切的说法。我会猜测你的意思是“当你从概览屏幕(a.k.a.,最近的任务列表)中移除你的应用程序”。

一旦onReceive()回报,如果你没有在前台的活动,你没有运行的服务,您的流程中的重要性会下降到什么the documentation是指作为一个“缓存进程”。您的流程有资格在任何时候终止。一旦您的流程终止,您的Timer就会消失。因此,您编写的代码将不可靠,因为您的过程可能会在您的30秒窗口内终止。

其他可能性包括:

  • 你正在做的设置您的应用程序的屏幕上“当应用程序被杀害”别的东西的行为就像“强制停止”不。通常情况下,“强制停止”按钮是强制停止应用程序的唯一方式,但偶尔设备制造商会做一些愚蠢的事情,并强制停止其他事情发生的事情(例如设备提供的“应用程序管理器”)。一旦您的应用程序被强制停止,您的代码将永远不会再次运行,直到用户从主屏幕启动器图标启动应用程序或设备上的其他设备使用明确的Intent启动您的某个组件。

  • 如果设备入睡,您的Timer将不会被调用,直到设备再次唤醒。

+0

“当应用程序被杀害”我的意思是从最近的任务列表中删除它。有没有办法运行Timer(Scheduler)。那么,该通知会弹出在状态栏中,还是有其他方法可以这样做? –

+2

@KabindraSimkhada:使用'AlarmManager'或'JobScheduler'。 – CommonsWare