当应用程序关闭时发送通知

29

当应用被完全关闭时,如何通过编程方式发送通知?

例如:用户关闭了应用程序,也在Android任务管理器中关闭了应用程序,并等待。应用程序应该在X秒后或应用程序检查更新时发送通知。

我尝试使用以下代码示例,但是:

如果可以,请尝试通过示例解释一下,因为初学者(像我一样)可以更轻松地学习。

4个回答

18

您可以使用此服务,所需操作是在活动生命周期的onStop()中启动该服务。使用以下代码: startService(new Intent(this, NotificationService.class)); 然后,您可以创建一个新的Java类并将此代码粘贴到其中:

public class NotificationService extends Service {

    Timer timer;
    TimerTask timerTask;
    String TAG = "Timers";
    int Your_X_SECS = 5;


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);

        startTimer();

        return START_STICKY;
    }


    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");


    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        stoptimertask();
        super.onDestroy();


    }

    //we are going to use a handler to be able to run in our TimerTask
    final Handler handler = new Handler();


    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 5000, Your_X_SECS * 1000); //
        //timer.schedule(timerTask, 5000,1000); //
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {

                        //TODO CALL NOTIFICATION FUNC
                        YOURNOTIFICATIONFUNCTION();

                    }
                });
            }
        };
    }
}

接下来,您只需要将该服务与manifest.xml结合即可:

<service
            android:name=".NotificationService"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="your.app.domain.NotificationService" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

1
谢谢!我已经测试了你的代码,它可以在我的应用程序中正常运行! - Excel1
1
根据这篇文章所述,“TimerTask - 不在UIThread中运行,也不可靠。共识是永远不要使用TimerTask。” Nikhil Gupta的答案更好。 - Bondolin

8
您可以使用闹钟管理器来完成此操作[未在最新的Android版本和发布版上进行测试,这是一个相当古老的答案]。按照以下步骤进行:
1.使用闹钟管理器创建X秒后的闹钟。 Intent intent = new Intent(this, AlarmReceiver.class); intent.putExtra("NotificationText", "一些文本"); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ledgerId, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, 'X毫秒', pendingIntent);
2.在您的应用程序中使用AlarmBroadCast接收器。
请在清单文件中声明:
<receiver android:name=".utils.AlarmReceiver">
    <intent-filter>
        <action android:name="android.media.action.DISPLAY_NOTIFICATION" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>
  1. In the broadcast receiver's on receive, you can create the notification.

    public class AlarmReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {
         // create notification here
     }
    

    }


谢谢你的回答。我尝试了你的代码,它已经可以工作了。我决定使用 @Vaibhav Kadam 的代码,因为对于我的个人使用来说更具吸引力。 - Excel1
2
这似乎是更受欢迎的方法。https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks 提供了更详细的描述。 - Bondolin
我认为这个在2021年已经不再起作用了,当应用程序关闭时,闹钟管理器将无法运行。 - user1034912

1
根据评论中Bondolin提供的网站和Nikhil Gupta的答案,将属性android:process=":remote"添加到receiver中使得即使应用程序完全关闭也能够发布通知。
<receiver
    android:name = ".utils.AlarmReceiver"
    android:process=":remote" >  <!-- this line is important -->
</receiver>

而且代码的其余部分基本相同。需要注意的一个重要事项是,类AlarmReceiver不应包含对MainActivity的任何引用,因为当应用程序关闭时,MainActivity类未被实例化。NullPointerException如果您在应用程序关闭时尝试在AlarmReceiver类中引用MainActivity,将抛出异常。

0

您可以使用服务检查活动应用程序,并在活动未运行时显示通知。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接