应用关闭时通知被取消

时间:2019-02-12 12:04:24

标签: java android

我在我的应用程序中使用Socket.io,并在我的应用程序类中使用Broadcast Receiver来查看从Sockets接收新更新时所做的广播。当我收到通知时,我想创建一个通知。

  • 我能够在8.0(Oreo)上创建通知

。当我关闭应用程序时,广播接收器将被注销,套接字将被断开。但是问题在于,无论何时关闭应用程序或在后台运行,通知都将消失

使用套接字连接,我可以创建通知,但是当应用程序进入后台时,这些通知将被取消/取消。

我检查了 setAutoCancel cancel cancelAll 的代码,但没有在任何地方调用它们

应用程序类

//... Notification Channels
public static final String STATE_SERVICE_ID = "StateChannel";
private final String STATE_SERVICE_NAME = "Change State";

public static final String LIVE_UPDATES_ID = "LiveUpdateChannel";
private final String LIVE_UPDATE_NAME = "Live Updates";

public static final String LIVE_FLIGHTS_ID = "FlightChannel"; //..Channel on which I want to show the notification
private final String LIVE_FLIGHTS_NAME = "Flight Updates";


private NotificationManagerCompat notificationManager;
private NotificationCompat.Builder flightNotification;//.. Will be using this to create a notification


 //.. Creating Notifications in OnCreate() of Application
private void createNotificationChannels() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel stateChannel = new NotificationChannel(
                STATE_SERVICE_ID,
                STATE_SERVICE_NAME,
                NotificationManager.IMPORTANCE_LOW
        );

        NotificationChannel updatesChannel = new NotificationChannel(
                LIVE_UPDATES_ID,
                LIVE_UPDATE_NAME,
                NotificationManager.IMPORTANCE_LOW
        );

        NotificationChannel flightChannel = new NotificationChannel(
                LIVE_FLIGHTS_ID,
                LIVE_FLIGHTS_NAME,
                NotificationManager.IMPORTANCE_HIGH
        );

        NotificationManager manager = getSystemService(NotificationManager.class);
        List<NotificationChannel> notificationChannels = new ArrayList<>();
        notificationChannels.add(stateChannel);
        notificationChannels.add(updatesChannel);
        notificationChannels.add(flightChannel);

        assert manager != null;
        manager.createNotificationChannels(notificationChannels);

        notificationManager = NotificationManagerCompat.from(this);
    }
}

//.. I copied this code from Google Docs
private void createNotificationTypes() {
    flightNotification = new NotificationCompat.Builder(this, LIVE_FLIGHTS_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("Flight Updates")
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH);
}

//... Inner Class for receiving Broadcasts
private class flightReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        if(String.valueOf(BuildConfig.APPLICATION_ID+BuildConfig.VERSION_CODE).equals(intent.getAction())){
            flightNotification.setContentText("Small Text");
            notificationManager.notify(1, flightNotification.build());
        }

    }
}

预期结果:创建通知后,即使关闭应用程序,通知仍会保留在那里。

实际结果:正在创建通知,但是一旦应用关闭,通知就会关闭。

编辑

如果有人想要应用程序类的完整文件,则为:

    import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.arch.lifecycle.ProcessLifecycleOwner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;

import com.android.volley.VolleyError;
import com.avileapconnect.com.BuildConfig;
import com.avileapconnect.com.Interfaces.I_NetworkResponse;
import com.avileapconnect.com.NetworkManager;
import com.avileapconnect.com.R;
import com.avileapconnect.com.ServiceLayer.SocketService_Test;
import com.avileapconnect.com.services.ForeSocketService;
import com.avileapconnect.com.services.ForeStateService;

import java.util.ArrayList;
import java.util.List;

import static com.avileapconnect.com.services.ForeSocketService.DUMMY_KEY;

public class LifeCycleObserver extends Application
        implements LifecycleObserver, I_NetworkResponse {

    private String state = "foreground";
    SharedPreferences pref;
    private String Response = "";

    public static final String STATE_SERVICE_ID = "StateChannel";
    private final String STATE_SERVICE_NAME = "Change State";

    public static final String LIVE_UPDATES_ID = "LiveUpdateChannel";
    private final String LIVE_UPDATE_NAME = "Live Updates";

    public static final String LIVE_FLIGHTS_ID = "FlightChannel";
    private final String LIVE_FLIGHTS_NAME = "Flight Updates";

    private NetworkManager networkManager;

    private flightReceiver receiver;
    private NotificationManagerCompat notificationManager;
    private NotificationCompat.Builder flightNotification;


    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        pref = getSharedPreferences(Keys.getPreferenceFileName(), Context.MODE_PRIVATE);

        networkManager = new NetworkManager(this,this);

        receiver = new flightReceiver();
        createNotificationChannels();
        createNotificationTypes();
    }

    private void createNotificationChannels() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel stateChannel = new NotificationChannel(
                    STATE_SERVICE_ID,
                    STATE_SERVICE_NAME,
                    NotificationManager.IMPORTANCE_LOW
            );

            NotificationChannel updatesChannel = new NotificationChannel(
                    LIVE_UPDATES_ID,
                    LIVE_UPDATE_NAME,
                    NotificationManager.IMPORTANCE_LOW
            );

            NotificationChannel flightChannel = new NotificationChannel(
                    LIVE_FLIGHTS_ID,
                    LIVE_FLIGHTS_NAME,
                    NotificationManager.IMPORTANCE_HIGH
            );



            NotificationManager manager = getSystemService(NotificationManager.class);
            List<NotificationChannel> notificationChannels = new ArrayList<>();
            notificationChannels.add(stateChannel);
            notificationChannels.add(updatesChannel);
            notificationChannels.add(flightChannel);

            assert manager != null;
            manager.createNotificationChannels(notificationChannels);

            notificationManager = NotificationManagerCompat.from(this);

        }
    }

    private void createNotificationTypes() {
        flightNotification = new NotificationCompat.Builder(this, LIVE_FLIGHTS_ID)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentTitle("Flight Updates")
                .setOngoing(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onAppBackgrounded() {
        //App in background
        handleServicesForBackground();

        SocketService_Test.getInstance().disconnectSocket();
        Intent socketIntent = new Intent(this, ForeSocketService.class);
        stopService(socketIntent);

//        unregisterReceiver(receiver);
    }

    public void handleServicesForBackground() {
        state = "background";
        if(!pref.getString(Keys.getPreferenceMobileNoKey(),"").equals("")){
            Intent serviceIntent = new Intent(this, ForeStateService.class);
            serviceIntent.putExtra("inputExtra",state);
            startService(serviceIntent);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onAppForegrounded(){
        //App in Foreground
        Log.i("Lifecycle Observer","onStart Called");

        handleServicesForForeground(pref);

        IntentFilter filter = new IntentFilter(String.valueOf(BuildConfig.APPLICATION_ID
                + BuildConfig.VERSION_CODE));
        registerReceiver(receiver,filter);
    }

    public void handleServicesForForeground(SharedPreferences pref) {
        String state = "foreground";

        if(!pref.getString(Keys.getPreferenceMobileNoKey(),"").equals("")){
           networkManager.changeState(this.pref.getString(Keys.getPreferenceMobileNoKey(),""),
                   state);

            Intent socketIntent = new Intent(this, ForeSocketService.class);
            startService(socketIntent);
        }
    }

    @Override
    public void getNetworkSuccessResponse(String TAG, String successResponse, String TAGforApi) { }

    @Override
    public void getNetworkFailResponse(String TAG, VolleyError failResponse, String TAGforApi) { }


    private class flightReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(String.valueOf(BuildConfig.APPLICATION_ID+BuildConfig.VERSION_CODE).equals(intent.getAction())){
//                String content = intent.getStringExtra(DUMMY_KEY);

                flightNotification.setContentText("Small Text");
                notificationManager.notify(1, flightNotification.build());
            }

        }
    }
}

0 个答案:

没有答案