如何在应用程序关闭时显示通知?

时间:2021-01-18 10:40:25

标签: android android-service

我想在 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());
}
}

1 个答案:

答案 0 :(得分:0)

当应用程序在后台时,您的服务被终止。

您需要在 startForeground 方法上调用 startCommand

This is an example to see