0

我最近一直在制作Android应用程序.. 其中我使用了Pending Intent和Alarm Manager。 我需要有多个挂起的意图,所以我正在使用FLAG_ONE_SHOT。报警管理器将按照提及的间隔发送广播。还有,我正在使用intent的setAction()方法并将currentTimeMillis()作为参数传递。我有相应的广播接收器。问题是,一旦应用程序关闭,或从最近的托盘中删除,广播接收器不运行。 的代码如下:待定意图和报警管理器

  1. setAlarm:

    private void setupAlarm(int seconds) { 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    Intent intent = new Intent(getBaseContext(), OnAlarmReceive.class); 
    //PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT); 
    intent.setAction(Long.toString(System.currentTimeMillis())); 
    intent.putExtra("id", ID); 
    
    PendingIntent pendingIntent = PendingIntent.getBroadcast(ChatActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT); 
    
    Log.e(TAG, "Setup the Alarm"); 
    
    Calendar calendar = Calendar.getInstance(); 
    calendar.add(Calendar.SECOND, seconds); 
    
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);} 
    
  2. 广播接收机

    public void onReceive(Context context, Intent intent) { 
    
    String id = intent.getStringExtra("id"); 
    Log.e(TAG,"On the verge of deleting the message with id: "+id); 
    SQLiteDatabase database = context.openOrCreateDatabase("/sdcard/userlists.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); 
    database.execSQL("DELETE FROM " + "MESSAGE" + " WHERE " + "id" + "= '" + id + "'"); 
    
    broadcaster = LocalBroadcastManager.getInstance(context); 
    intent = new Intent(COPA_RESULT); 
    broadcaster.sendBroadcast(intent);} 
    
  3. 的Manifest.xml

    <receiver android:name=".OnAlarmReceive" android:enabled="true" android:exported="true"/> 
    

请帮帮我。即使应用已关闭,我也需要广播公司来完成这项工作。

+0

使用'service'! –

+0

因此,如果不使用服务,我无法接收广播? 如果是这样,你能提供步骤吗? –

回答

0

这是流程生命周期错误,其中,当应用程序进入后台回收内存

您需要安排JobService接收工作应用程序是否处于活动状态

系统可以杀死进程

,由工艺的官方document和应用程序生命周期

流程生命周期错误的一个常见示例是BroadcastReceiver ,它在其 BroadcastReceiver.onReceive()方法中接收到Intent时启动线程,然后从 函数返回。一旦它返回,系统认为BroadcastReceiver 不再处于活动状态,因此,其主机进程不再需要 (除非其他应用程序组件处于活动状态)。因此,系统 可能会随时终止进程以回收内存,并且这样做会终止在进程中运行的衍生线程。解决此问题的解决方案 通常是从 BroadcastReceiver安排JobService,因此系统知道在该过程中仍有活动工作 正在完成。

这里是example你可以按照完成要求

+0

你明白了吗? –

+0

是的......非常非常抱歉,迟到的回复......但非常感谢你! –