gpt4 book ai didi

android - 应用程序关闭时如何获取android通知?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:37:59 25 4
gpt4 key购买 nike

我从 webserivce 获取日期和时间形式的数据,这意味着对于某个特定日期我有一些插槽集。下图给出了详细的解释。 enter image description here

在这里,我在每个日期都有一些时间安排。这里我想要的是在特定的日期和时间显示通知。如果来自数据库的响应包含明天日期,例如 07/12/2012 上午 11:00。我需要在那个时候显示通知。

我对通知管理器有一些想法,我正在使用的代码是..

主.java

      NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_action_search, "A New Message!", System.currentTimeMillis());

Intent notificationIntent = new Intent(this, Main.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(Main.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);

但在这里我也需要在应用关闭时收到通知。所以,任何人都可以帮助我。

最佳答案

向您的应用程序添加(启动的)服务。即使用户退出了您的应用程序,该服务仍将在后台运行。

此外,您还可以实现一个 BroadcastReceiver,它会监听手机的 Intent 并让您的服务在手机启动时启动!

MyService.java

public class MyService extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId){
// START YOUR TASKS
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
// STOP YOUR TASKS
super.onDestroy();
}

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

BootReceiver.java

public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("your.package.MyService");
context.startService(serviceIntent);
}
}
}
}

AndroidManifest.xml

//在 list 标签中

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

//在你的应用标签中

<service android:name=".MyService">
<intent-filter>
<action android:name="your.package.MyService" />
</intent-filter>
</service>

<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true"
android:label="BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

如果你想从一个 Activity 开始你的服务,只需使用

private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

if (!isMyServiceRunning()){
Intent serviceIntent = new Intent("your.package.MyService");
context.startService(serviceIntent);
}

关于android - 应用程序关闭时如何获取android通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13741875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com