安卓 前台服务 通知

前台服务 通知遇到的问题

大家好,我这复习Service时候,看到了 前台服务,于是写了一下,首先新建一个 服务:

public class QianService extends Service {
    
    


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    
    
        Log.d("info","前台服务  onBind");
        return null;
    }

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        Log.d("info","前台服务  onCreate");

        // 初始化
        NotificationManager messageNotificatioManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("服务标题");
        builder.setContentText("哈哈哈哈 测试服务");
        builder.setWhen(System.currentTimeMillis());
        builder.setChannelId("5996773");

        Intent notificationIntent = new Intent(this, MainActivity2.class);
        PendingIntent pt = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pt);
        Notification notification = builder.build();

        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
    
        Log.d("info","前台服务  onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
    
    
        super.onDestroy();
        Log.d("info","前台服务  onDestroy");
    }

}

第二步 ,在AndroidMainfest.xml注册:

<!--        前台服务-->
        <service android:name=".service.QianService"
            android:enabled="true"
            android:exported="true"></service>

第三步 ,然后运行,开启 服务:

//前台服务 通知栏提示
    Intent intent = new Intent(this,QianService.class);
    startService(intent);

就这样,然后我发现,打开服务后,闪退了,额 思考一下, 哦 我似乎没有开启权限;
如下是我的 开启通知权限方法:

public class UtilsNew {
    
    

    //监测通知权限
    public static boolean isPermissionOpen(Context context) {
    
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
            return NotificationManagerCompat.from(context).getImportance() != NotificationManager.IMPORTANCE_NONE;
        }
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    public static void openPermissionSetting(Context context) {
    
    
        try {
    
    
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //直接跳转到应用通知设置的代码:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
                localIntent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                localIntent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                context.startActivity(localIntent);
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    
    
                localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                localIntent.putExtra("app_package", context.getPackageName());
                localIntent.putExtra("app_uid", context.getApplicationInfo().uid);
                context.startActivity(localIntent);
                return;
            }
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
    
    
                localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                localIntent.addCategory(Intent.CATEGORY_DEFAULT);
                localIntent.setData(Uri.parse("package:" + context.getPackageName()));
                context.startActivity(localIntent);
                return;
            }

            //4.4以下没有从app跳转到应用通知设置页面的Action,可考虑跳转到应用详情页面,

            if (Build.VERSION.SDK_INT >= 9) {
    
    
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
                context.startActivity(localIntent);
                return;
            }

            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());


        } catch (Exception e) {
    
    
            e.printStackTrace();
            System.out.println(" cxx   pushPermission 有问题");
        }
    }

}

然后呢,我再试测试,发现 哦 不行啊,提示错误:

Permission Denial: startForeground from pid=27589, uid=10168 requires android.permission.FOREGROUND_。。。。

于是乎 搜了一下,哦 ,需要在 AndroidManifest.xml添加权限:

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

测试之后 发现,额 为何还是 闪退,哈哈哈哈 好吧, 最后一次了:
如下 添加一个 channel即可:

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
        NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableLights(true);//是否在桌面icon右上角展示小红点
        channel.setLightColor(Color.GREEN);//小红点颜色
        channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
        messageNotificatioManager.createNotificationChannel(channel);
    }

下面我再 贴上 服务类的完整代码吧:

package com.example.androidstudy.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.example.androidstudy.R;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

public class QianService extends Service {
    
    


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    
    
        Log.d("info","前台服务  onBind");
        return null;
    }

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        Log.d("info","前台服务  onCreate");

        // 初始化
        NotificationManager messageNotificatioManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
            NotificationChannel channel = new NotificationChannel("5996773", "安卓10a", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);//是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN);//小红点颜色
            channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
            messageNotificatioManager.createNotificationChannel(channel);
        }

//
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("服务标题");
        builder.setContentText("哈哈哈哈 测试服务");
        builder.setWhen(System.currentTimeMillis());
        builder.setChannelId("5996773");

        Intent notificationIntent = new Intent(this, MainActivity2.class);
        PendingIntent pt = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pt);
        Notification notification = builder.build();

        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
    
        Log.d("info","前台服务  onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
    
    
        super.onDestroy();
        Log.d("info","前台服务  onDestroy");
    }

}

希望能给大家带来 作用,因为这个小问题吧, 困扰了我好一会儿,

猜你喜欢

转载自blog.csdn.net/mawlAndroid/article/details/117957111