草庐IT

android - 每天在特定时间触发本地通知,即使应用已关闭

coder 2023-12-03 原文

我必须每天在特定时间(例如早上 7 点) 向我的应用程序的用户显示通知,即使我的应用程序未运行。(关闭)

由于通知的内容是用户特定的,我不能使用 (GCM)push

我已经阅读了很多教程和答案,但是当应用程序关闭(未运行)时我无法显示通知。

编辑:使用下面的代码我可以在我的应用程序运行时创建通知,如果我关闭我的应用程序通知会显示

这是我的主要 Activity

public class MainActivity extends AppCompatActivity {
Button setAlarm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setAlarm = (Button) findViewById(R.id.set_alarm);
    setAlarm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }
    });
}
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}
}

在这里,当我点击设置警报按钮时,我的 NotificationEventReciver 将调用

public class NotificationEventReceiver extends WakefulBroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";


public static void setupAlarm(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, NotificationEventReceiver.class);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getTriggerAt(new Date()), 2 * 60 * 1000, alarmIntent);

}
private static long getTriggerAt(Date now) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 17);
    calendar.set(Calendar.MINUTE, 10);
    System.err.println(now.getTime()+"----->"+ calendar.getTimeInMillis());
    return calendar.getTimeInMillis();
}

public static void cancelAlarm(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent alarmIntent = getStartPendingIntent(context);
    alarmManager.cancel(alarmIntent);
}


private static PendingIntent getStartPendingIntent(Context context) {
    Intent intent = new Intent(context, NotificationEventReceiver.class);
    intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

public static PendingIntent getDeleteIntent(Context context) {
    Intent intent = new Intent(context, NotificationEventReceiver.class);
    intent.setAction(ACTION_DELETE_NOTIFICATION);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

@Override
public void onReceive(Context context, Intent intent) {
    Intent serviceIntent =  NotificationIntentService.createIntentStartNotificationService(context);
    if (serviceIntent != null) {
        System.err.println("onReceive inside not null");
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, serviceIntent);
    }
}
}

我的服务类将在闹钟响起时运行。

public class NotificationIntentService extends IntentService {

private static final int NOTIFICATION_ID = 1;
private static final String ACTION_START = "ACTION_START";
private static final String ACTION_DELETE = "ACTION_DELETE";

public NotificationIntentService() {
    super(NotificationIntentService.class.getSimpleName());
}

public static Intent createIntentStartNotificationService(Context context) {
    Intent intent = new Intent(context, NotificationIntentService.class);
    intent.setAction(ACTION_START);
    return intent;
}

@Override
protected void onHandleIntent(Intent intent) {
    System.err.println("onHandleIntent, started handling a notification event");
    try {
        String action = intent.getAction();
        if (ACTION_START.equals(action)) {
            System.err.println("enters the loop ACTION_START");
            processStartNotification();
        }
    } finally {
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }
}


private void processStartNotification() {
    // Do something. For example, fetch fresh data from backend to create a rich notification?
    System.err.println("inside the notify method");
    Intent mainIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("Scheduled Notification")
            .setAutoCancel(true)
            .setColor(getResources().getColor(R.color.colorAccent))
            .setContentText("This notification has been triggered by Notification Service")
            .setSmallIcon(R.drawable.ic_launcher);

    builder.setContentIntent(pendingIntent);

    final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(NOTIFICATION_ID, builder.build());
}
}

最佳答案

在您的 setUpAlarm 方法中试试这个-

AlarmManager am = (AlarmManager) cont
                        .getSystemService(cont.ALARM_SERVICE);

 Intent intent = new Intent(cont, MyReceiver.class);    
intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER); 

boolean isWorking = (PendingIntent.getBroadcast(cont, 1001, 

    intent, PendingIntent.FLAG_NO_CREATE) != null);
    if (isWorking) { 
    // first cancel previous alarm 
    Intent intent = new Intent(cont, MyReceiver.class);// the same as up 
    intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER);// the same as up 
    PendingIntent pI = PendingIntent.getBroadcast(cont, 1001, 
    intent, PendingIntent.FLAG_CANCEL_CURRENT);// the same as up 
    am.cancel(pI);// important 
    pI.cancel();// important 
    } else { 
    Intent intent1 = new Intent(cont, MyReceiver.class); 
    intent1.setAction(MyReceiver.ACTION_ALARM_RECEIVER); 
    
    PendingIntent pendingIntent = PendingIntent 
    .getBroadcast(cont, 0, intent1, 
    PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager am = (AlarmManager) cont 
    .getSystemService(cont.ALARM_SERVICE); 
    
    am.setRepeating(AlarmManager.RTC_WAKEUP, 
    calendar.getTimeInMillis(), 
    AlarmManager.INTERVAL_DAY, pendingIntent); 
    }

关于android - 每天在特定时间触发本地通知,即使应用已关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37340760/

有关android - 每天在特定时间触发本地通知,即使应用已关闭的更多相关文章

  1. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  2. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  3. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  6. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  7. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  8. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  9. ruby - 是否可以覆盖 gemfile 进行本地开发? - 2

    我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI

  10. ruby-on-rails - 将 Ruby 中的日期/时间格式化为 YYYY-MM-DD HH :MM:SS - 2

    这个问题在这里已经有了答案:Railsformattingdate(4个答案)关闭4年前。我想格式化Time.Now函数以显示YYYY-MM-DDHH:MM:SS而不是:“2018-03-0909:47:19+0000”该函数需要放在时间中.现在功能。require‘roo’require‘roo-xls’require‘byebug’file_name=ARGV.first||“Template.xlsx”excel_file=Roo::Spreadsheet.open(“./#{file_name}“,extension::xlsx)xml=Nokogiri::XML::Build

随机推荐