android - 应用关闭时如何显示通知?
问题描述
我想在 firebase 中的子项值发生更改时显示通知。我使用了下面的代码,它在应用程序处于前台或后台时工作,并且即使应用程序关闭,它也在 android 7 [未在 7 以下测试] 中工作。但是在 android 9 和 10 中,当我通过从后台滑动关闭应用程序时,代码没有显示通知。有时在 android 9 中,它会在关闭并从后台删除应用程序后显示一段时间的通知。无论应用程序是否正在运行,如何显示通知?
public class ServiceManager extends Service {
public ServiceManager() {}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
showNotificationChanges();
// Code to execute when the service is first created
}
@Override
public void onDestroy() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
System.out.println("called");
showNotificationChanges();
return START_STICKY;
}
private void stopService() {
}
public void getLastModifiedTime(final HomePage.MyCallback myCallback){
System.out.println("modified time called");
SharedPreferences spCD = getSharedPreferences("spCD",MODE_PRIVATE);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child(Objects.requireNonNull(spCD.getString("ccm", "Not found"))).child("cd").child("test").child("test1").child("test2");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
String data = snapshot.getValue().toString();
myCallback.onCallback(data);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public void showNotificationChanges() {
getLastModifiedTime(new HomePage.MyCallback() {
@Override
public void onCallback(String roll) {
SharedPreferences spExtra = getSharedPreferences("spExtra",MODE_PRIVATE);
if(!spExtra.getString("1","No changes").equals(roll)){
SharedPreferences.Editor editor = spExtra.edit();
editor.putString("1",roll);
editor.apply();
showNotification(getApplicationContext());
//
}
int time;
if(isConnected()){
time = 10000;
}
else{
time = 120000;
}
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
showNotificationChanges();
}
},time);
}
});
}
public boolean isConnected(){
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M) {
Network nw = connectivityManager.getActiveNetwork();
if (nw == null) return false;
NetworkCapabilities actNw = connectivityManager.getNetworkCapabilities(nw);
return actNw != null &&
(actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH));
}
else {
try {
NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
return nwInfo != null && nwInfo.isConnected();
}
catch (Exception ignored){
return false;
}
}
}
void showNotification(Context context) {
String CHANNEL_ID = "channel";// The id of the channel.
CharSequence name = context.getResources().getString(R.string.app_name);// The user-visible name of the channel.
NotificationCompat.Builder mBuilder;
Intent notificationIntent = new Intent(context, ShowRoutine.class);
Bundle bundle = new Bundle();
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 26) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(mChannel);
mBuilder = new NotificationCompat.Builder(context,CHANNEL_ID)
.setSmallIcon(R.drawable.routine_icon)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setContentTitle("Schedule modified");
} else {
mBuilder = new NotificationCompat.Builder(context,CHANNEL_ID)
.setSmallIcon(R.drawable.routine_icon)
.setPriority(Notification.PRIORITY_HIGH)
.setContentTitle("Schedule modified");
}
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("CR just modified something in routine");
mBuilder.setAutoCancel(true);
mNotificationManager.notify(1, mBuilder.build());
}
}
解决方案
推荐阅读
- haskell - 为什么 GHC 不能确定在这个案例语句中使用哪个字段?
- python-3.x - 使用布尔值而不是 'if' 'else'
- mysql - SQL - 如何根据两个表获得总和?
- oracle - 我想通过添加 1000000 'FİLE_NO' 和 'PROT_NO' 列来更新这些表
- python - 返回经过训练的三元组标记器时出错:UnpicklingError: invalid load key, '\x0a'
- python - 如何修复python中的“字符串反转”代码?
- wordpress - Wordpress 将特色图像作为尺寸数组获取
- c++ - c++ 矢量仅在 64 版本中崩溃 - SIGBUS
- ios - 在应用程序中添加 Fabric 时,链接器命令失败,退出代码为 1(使用 -v 查看调用)
- reactjs - Material-UI TexField Select - 展开时显示不同