【发布时间】:2017-03-15 14:16:53
【问题描述】:
所以,我今天已经尝试实现这一目标至少五个小时,并且我已经尝试了任何在任何地方找到的解决方案。
我正在编写一个小时钟应用程序,使用 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