应用程序关闭时,BroadcastReceiver 不会启动活动

问题描述 投票:0回答:1

所以,今天我已经尝试了至少五个小时来实现这一目标,并且我已经尝试了任何在任何地方都能找到的解决方案。

我正在编写一个小时钟应用程序,使用 AlarmManager 使应用程序响铃。当我的应用程序打开或最小化时它工作正常。我试图让它在应用程序关闭时工作,这就是问题所在。因此,有一段设置 AlarmManager 的代码:

    AlarmManager am = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctxt, AlarmService.class);
    PendingIntent pen = PendingIntent.getBroadcast(ctxt, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    am.setExact(AlarmManager.RTC_WAKEUP, nextRing.getTime(), pen);

(这里,ctxt是上下文,我尝试了getApplicationContext()和getBaseContext(),而nextRing.getTime()是代表日期的long)

然后,我有我的 AlarmService 类(它曾经是一个服务,解释了名称,但现在是一个 BroadcastReceiver,我现在不想重命名它)

public class AlarmService extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    /*Intent cust = new Intent(context, CustomIntent.class);
    context.startService(cust);*/
    Bundle extras = intent.getExtras();
    Intent newIntent = new Intent(context, AlarmActivity.class);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    newIntent.putExtra("AlarmName", extras.getString("AlarmName"));
    context.startActivity(newIntent);
  }

}

所以这是仅使用BroadcastReceiver的尝试,这显然不起作用,所以我尝试添加一个IntentService(在顶部注释掉代码),它具有以下代码

public class CustomIntent extends IntentService {
  public CustomIntent() {
    super("CustomIntent");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
    Intent newIntent = new Intent(getBaseContext(), AlarmActivity.class);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getApplication().startActivity(newIntent);
  }
}

...这也不起作用!最后,这是我使用的清单:

<application>
[Here goes stuff that have nothing to do with my bug]
    <receiver android:name=".custom_classes.AlarmService"/>
    <service
      android:name="com.group9.abclock.custom_classes.CustomIntent"
      android:enabled="true" >
      <intent-filter>
        <action android:name="com.group9.abclock.custom_classes.CustomIntent" />
      </intent-filter>
    </service>
  </application>

很抱歉这篇(非常)长的文章,但我想我应该解释一下我尝试过的一切。如果您能提供帮助,请先致谢!

android broadcastreceiver alarmmanager android-pendingintent intentservice
1个回答
1
投票

如果你的应用程序关闭,你无法触发BroadcastReceiver,因为它没有注册,并且你无法使用Context方法,因为没有Context。

如果您想在应用程序关闭时执行任务,则必须使用服务创建另一个项目,并与您的应用程序一起启动它。

服务在后台运行,直到有人杀死它,一旦它启动,就不再需要主应用程序了。因此必须在该服务中实现响铃功能。

请记住,由于 Doze 模式,AlarmManager.setExact 与 API 23 并不完全相同。

© www.soinside.com 2019 - 2024. All rights reserved.