java - Forerground 服务初始化后无法更新通知文本;上下文问题

标签 java android android-notifications nanohttpd foreground-service

我有一个简单的 NanoHTTPD 服务器作为前台服务运行。

当收到对服务器的新请求时,我在用新内容更新通知时遇到了问题。

前台服务启动并显示通知。没问题。但是以后不能更新它们。

文件结构
- 主要 Activity
- NanoServer (服务器实现)
- NanoService (前台服务类)
- NotificationProvider (处理通知的单独类)

NanoServer.java

    public Context context = getContext();
    public NotificationProvider notificationProvider;

    public NanoServer(int port) {
        super(8089);
    }

    @Override
    public Response serve(String uri, Method method,
                          Map<String, String> header, Map<String, String> parameters,
                          Map<String, String> files) {
        String answer = "";
        String msg;

        // doesnt work with the context. something wrong here I guess????
        notificationProvider = new NotificationProvider();
        notificationProvider.setNotification(context, "Title", uri, 0);

        FileInputStream fis = null;

        try {
            fis = new FileInputStream(uri);
            Log.w(TAG, uri + " found");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return newChunkedResponse(Status.OK, "audio/mpeg", fis);

    }

    public Context getContext() {
        return context;
    }

纳米服务.java

    String TAG = "NANOSERVICE";
    public Context context = this;
    public Handler handler = null;
    public static Runnable runnable = null;
    PowerManager powerManager;
    PowerManager.WakeLock wakeLock;
    WifiManager.WifiLock wifiLock;

    private NanoServer nanoServer;
    public NotificationProvider notificationProvider;

    public NanoService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Start the httpd.
        try {
            nanoServer = new NanoServer(8089);
            nanoServer.start();
            Log.d(TAG, "Service with server started");
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Service failed to start.", Toast.LENGTH_LONG).show();
        }

        // Keep the CPU awake (but not the screen).
        powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();

        // Keep the WIFI turned on.
        WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TAG);
        wifiLock.acquire();

        notificationProvider = new NotificationProvider();
        notificationProvider.setNotification(this, "Title", "Message", 0);

        // had to extend notificationprovider with notification
        startForeground(1, notificationProvider);
        Log.d(TAG, "Foreground service running");

        return Service.START_STICKY;

    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        wakeLock.release();
        wifiLock.release();
        nanoServer.stop();
    }

NotificationProvider.java

public class NotificationProvider extends Notification {
    String TAG = "NOTIFICATIONPROVIDER";
    public NotificationProvider() {
    }

    public void setNotification(Context context, String notificationTitle, String notificationMessage, int notificationRequestCode){
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle(notificationTitle)
                        .setContentText(notificationMessage)
                        .setTicker("My service")
                        .setColor(101)
                        .setWhen(System.currentTimeMillis())
                        .setOngoing(true)
                        .setPriority(NotificationCompat.PRIORITY_MAX);

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, notificationRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
        Log.d(TAG, "Got new Notification");
    }
}

最佳答案

我认为最简单的解决方案是使用相同的构建器方法来更新通知。

使用这个更新的 NotificationProvider

NanoService(或其他任何地方)中将 new NotificationProvider() 更改为 NotificationProvider.getInstance()

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.iroid.videoeditor.R;
import com.iroid.videoeditor.main.MainActivity;

public class NotificationProvider extends Notification {

    private static NotificationProvider sInstance;

    private NotificationCompat.Builder mBuilder;
    private String TAG = "NOTIFICATIONPROVIDER";

    public static NotificationProvider getInstance() {
        if (sInstance == null)
            sInstance = new NotificationProvider();

        return sInstance;
    }

    // Prevent creating new instances from outside
    private NotificationProvider() {
    }

    public void setNotification(Context context, String notificationTitle, String
            notificationMessage, int notificationRequestCode) {

        NotificationManager manager = (NotificationManager) context.getSystemService(Context
                .NOTIFICATION_SERVICE);

        if (mBuilder == null) {
            // Notification doesn't exists. Need to create one.
            mBuilder =
                    new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentTitle(notificationTitle)
                            .setContentText(notificationMessage)
                            .setTicker("My service")
                            .setColor(101)
                            .setWhen(System.currentTimeMillis())
                            .setOngoing(true)
                            .setPriority(NotificationCompat.PRIORITY_MAX);

            Intent intent = new Intent(context, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context,
                    notificationRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(contentIntent);

            manager.notify(0, mBuilder.build());
            Log.d(TAG, "Got new Notification");
        } else {
            // Notification exists. Simply update
        }
    }

}

关于java - Forerground 服务初始化后无法更新通知文本;上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51913053/

相关文章:

java - 标记 -> 转到行号

java - jackson 如何解析也是日期值的字段

java - JComboBox:希望第一个条目是空白条目

android - 在服务中使用游标或通过绑定(bind)到服务发送数据

java - 未在 JMS listner 非 Activity 类 android 中获取应用程序上下文

java - Java 中的不可变集合

java - ViewPager 没有显示任何内容

android - 如何将多个通知显示为一个组?

android - 在音乐停止播放之前要为通知编写什么代码

c# - 如何获取所有可用的蓝牙设备 android c# xamarin