Toast(源码)进程,Notification(源码)进程??

Toast跨进程,Notification跨进程 Notification跨进程通信?

-- Android 高级自定义Toast及源码解析- https://blog.csdn.net/qq_17250009/article/details/52753929
Android Toast源码分析- https://blog.csdn.net/wzy_1988/article/details/43341761
Toast问题深度剖析- https://www.jianshu.com/p/be2180c49409
 当 Toast 在 show 的时候,将这个请求放在 NotificationManager 所管理的队列中,并且为了保证 NotificationManager 能跟进
程交互, 会传递一个 TN 类型的 Binder 对象给 NotificationManager 系统服务。
//子线程中把Toast所需要的Looper对象给创建出来就可以了
new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(getContext(), "子线程显示", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
 }).start();

-- Notification
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setWhen()
.setSmallIcon()
.setLargeIcon()
.setContentIntent(pendingIntent);
RemoteViews remoteView = new RemoteViews(getPackageName,  R.layout.custom);
remoteView.setTextViewText(R.id.tv_title,  “通知标题”);
remoteView.setImageViewResource(R.id.iv_icon,  R.drawable.icon);
remoteView.setOnClickPendingIntent(R.id.iv_icon, pendingIntent);
builder.setContent(remoteView);
manager.notify(tag, id, builder.build());      RemoteViews不支持自定义View等复杂View
一、通知的选择
1.不依赖系统版本都要显示同样UI的可以使用自定义通知(例如酷狗播放通知)
2.需要与安卓系统版本UI保持一致的使用系统通知(例如酷狗消息通知)
3.当你需要保护你的Service不被系统优先Kill掉,可以用service.startForeground(notification)
二、做通知栏拓展的时候尽可能考虑7.0的通知栏特性(因为这些都是官方针对人性化用户体验设计的)
三、当需要跨进程使用View的时候可以考虑RemoteViews
四、当通知权限受阻,考虑使用替代方案(悬浮窗等)
五、建立完善的权限询问机制(针对targetSdkVersion,提高效率且提升用户体验)

// ANdroid Service服务

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (Build.VERSION.SDK_INT < 18) {
        startForeground(GRAY_SERVICE_ID, new Notification());
    } else {
        Intent innerIntent = new Intent(context, AuxiliaryService.class);
        startService(innerIntent);
        Notification notification = new Notification();
        startForeground(GRAY_SERVICE_ID, notification);
    }
    return super.onStartCommand(intent, flags, startId);
}

/**
 * 辅助Service 用来开启一个通知 就结束   不要创建内部类  不然回收有问题
 */
public class AuxiliaryService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startNotification();
        return super.onStartCommand(intent, flags, startId);
    }
    /** 启动通知*/
    private void startNotification(){
        Notification notification = new Notification();
        this.startForeground(MQTTService.GRAY_SERVICE_ID, notification);
        stopSelf(); //关键  如果AuxiliaryService 没有与什么组件绑定  系统就会回收
        stopForeground(true);
    }
}

猜你喜欢

转载自blog.csdn.net/ShareUs/article/details/83275888