GL_BOOK_7

来源:互联网 发布:自动编程软件 编辑:程序博客网 时间:2024/06/10 00:18

通知
比较详细的 详见 这里写链接内容

Intent intent  = new Intent(this, MainActivity.class);//这里 PendingIntent 可以通过三种方式getActivity、getBroadcast\getservice        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);//通过new Notification(xx,xx,xx)这种构造传参的方式创建 已被弃用//通常用 v4包的 NotificationCompat 向下兼容的builder来创建NotificationCompat.Builder builder = new NotificationCompat.Builder(this);        builder.setWhen(System.currentTimeMillis());        //瞬时闪过的显示内容        builder.setTicker("tickerText");        builder.setSmallIcon(R.drawable.ic_launcher);        //通知栏里通知条目的标题        builder.setContentTitle("notification title");        //通知栏里通知条目的内容        builder.setContentText("Notification content");        //点击通知栏里条目 触发的意图        builder.setContentIntent(pi);        //点击清除通知栏通知  触发的意图//      builder.setDeleteIntent(pi);        //直接全屏显示的 通知意图//      builder.setFullScreenIntent(pi,true);//      builder.setPriority(Notification.PRIORITY_MAX);        builder.setAutoCancel(true)//点击后让通知将消失         //正在进行ornot        builder.setOngoing(false);        //自己手机是 4.4.2 版本 这种呼吸灯方法可行 不过颜色无效        builder.setLights(0xffff0000, 3000, 2000);        Notification notification =  builder.build();//      notification.flags |= Notification.FLAG_ONGOING_EVENT; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中   //      notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在点击了通知栏中的"清除通知"后,此通知不清除,经常与FLAG_ONGOING_EVENT一起使用           //点击自动清除        notification.flags |= Notification.FLAG_AUTO_CANCEL;        notification.flags |= Notification.FLAG_SHOW_LIGHTS;         //以下方法在4.4.2 华为 无效 //      notification.ledARGB = Color.BLUE;//      notification.ledOnMS = 3000;//      notification.ledOffMS = 2000;        //这个属性很重要 声音 震动 呼吸灯 或者全部和系统一致        notification.defaults = Notification.DEFAULT_LIGHTS;        mNotificationManager.notify(1, notification);

NotificationCompat.Builder类
NotificationCompat.Builder类可以更容易控制标志,以及帮助构建典型通知布局。以下是 NotificationCompat.Builder类的一些重要的和最常用的方法的一部分。

S.N. 常量& 描述
1 Notification build()
结合所有已设置的选项,并返回一个新的 Notification 对象
2 NotificationCompat.Builder setAutoCancel (boolean autoCancel)
设置此标志将使它以便当用户点击它在面板中的通知被自动取消
3 NotificationCompat.Builder setContent (RemoteViews views)
提供定制RemoteViews使用来代替标准之一
4 NotificationCompat.Builder setContentInfo (CharSequence info)
设置大文本的通知的右侧
5 NotificationCompat.Builder setContentIntent (PendingIntent intent)
提供一个PendingIntent通知被点击时发出
6 NotificationCompat.Builder setContentText (CharSequence text)
设置通知的文本(第二行),在一个标准的通知
7 NotificationCompat.Builder setContentTitle (CharSequence title)
设置通知的文本(第一行),在一个标准的通知
8 NotificationCompat.Builder setDefaults (int defaults)
设置将要使用的默认通知选项
9 NotificationCompat.Builder setLargeIcon (Bitmap icon)
设置显示在自动收报机和通知大图标
10 NotificationCompat.Builder setNumber (int number)
在通知的右侧设置大的数字
11 NotificationCompat.Builder setOngoing (boolean ongoing)
设置这是否是一个持续的通知
12 NotificationCompat.Builder setSmallIcon (int icon)
设置小图标在通知使用布局
13 NotificationCompat.Builder setStyle (NotificationCompat.Style style)
在构建时应用添加丰富的通知样式
14 NotificationCompat.Builder setTicker (CharSequence tickerText)
设置在第一个通知到达时显示在状态栏中的文本
15 NotificationCompat.Builder setVibrate (long[] pattern)
设置振动模式的使用
16 NotificationCompat.Builder setWhen (long when)
设置该事件发生的时间。在面板的通知是由这个时间进行排序

/** 显示大视图风格通知栏 */    public void showBigStyleNotify() {        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();        String[] events = new String[5];        for (int i = 0; i < events.length; i++) {            events[i]="LHY"+i;        }        // Sets a title for the Inbox style big view        inboxStyle.setBigContentTitle("大视图内容:");        // Moves events into the big view        for (int i=0; i < events.length; i++) {            inboxStyle.addLine(events[i]);        }        mBuilder.setContentTitle("测试标题")                .setContentText("测试内容")//              .setNumber(events.length)//显示数量                .setStyle(inboxStyle)//设置风格                .setTicker("测试通知来啦");// 通知首次出现在通知栏,带上升动画效果的        mNotificationManager.notify(notifyId, mBuilder.build());    }

自定义的通知栏

Notification的自定义布局是RemoteViews,和其他RemoteViews一样,在自定义视图布局文件中,仅支持FrameLayout、LinearLayout、RelativeLayout三种布局控件和AnalogClock、Chronometer、Button、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView和AdapterViewFlipper这些显示控件,不支持这些类的子类或Android提供的其他控件。否则会引起ClassNotFoundException异常

    public void shwoNotify(){        //先设定RemoteViews        RemoteViews view_custom = new RemoteViews(getPackageName(), R.layout.view_custom);        //设置对应IMAGEVIEW的ID的资源图片        view_custom.setImageViewResource(R.id.custom_icon, R.drawable.icon);//      view_custom.setInt(R.id.custom_icon,"setBackgroundResource",R.drawable.icon);        view_custom.setTextViewText(R.id.tv_custom_title, "今日头条");        view_custom.setTextViewText(R.id.tv_custom_content, "金州勇士官方宣布球队已经解雇了主帅马克-杰克逊,随后宣布了最后的结果。");        //设置显示//      view_custom.setViewVisibility(R.id.tv_custom_time, View.VISIBLE);//      view_custom.setLong(R.id.tv_custom_time,"setTime", System.currentTimeMillis());//不知道为啥会报错,过会看看日志        //设置number//      NumberFormat num = NumberFormat.getIntegerInstance();//      view_custom.setTextViewText(R.id.tv_custom_num, num.format(this.number));        mBuilder = new Builder(this);        mBuilder.setContent(view_custom)                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))                .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示                .setTicker("有新资讯")                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级                .setOngoing(false)//不是正在进行的   true为正在进行  效果和.flag一样                .setSmallIcon(R.drawable.icon);        Notification notify = mBuilder.build();        notify.contentView = view_custom;//      notify.icon = R.drawable.icon;//      notify.contentIntent = getDefalutIntent(Notification.FLAG_AUTO_CANCEL);        mNotificationManager.notify(notifyId, notify);    }

带有button按钮的自定义 配合 broadcast使用

/**     * 带按钮的通知栏     */    public void showButtonNotify(){        NotificationCompat.Builder mBuilder = new Builder(this);        RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_button);        mRemoteViews.setImageViewResource(R.id.custom_song_icon, R.drawable.sing_icon);        //API3.0 以上的时候显示按钮,否则消失        mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, "周杰伦");        mRemoteViews.setTextViewText(R.id.tv_custom_song_name, "七里香");        //如果版本号低于(30),那么不显示按钮        if(BaseTools.getSystemVersion() <= 9){            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.GONE);        }else{            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.VISIBLE);            //            if(isPlay){                mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.btn_pause);            }else{                mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.btn_play);            }        }        //点击的事件处理        Intent buttonIntent = new Intent(ACTION_BUTTON);        /* 上一首按钮 */        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);        //这里加了广播,所及INTENT的必须用getBroadcast方法        PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_prev, intent_prev);        /* 播放/暂停  按钮 */        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);        PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);        /* 下一首 按钮  */        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);        PendingIntent intent_next = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);        mBuilder.setContent(mRemoteViews)                .setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT))                .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示                .setTicker("正在播放")                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级                .setOngoing(true)                .setSmallIcon(R.drawable.sing_icon);        Notification notify = mBuilder.build();        mNotificationManager.notify(200, notify);    }

PendingIntent.getBroadcast 参数中的 requestcode 也是不同的
需要注册一个接受者

/**     *   广播监听按钮点击时间      */    public class ButtonBroadcastReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            // TODO Auto-generated method stub            String action = intent.getAction();            if(action.equals(ACTION_BUTTON)){                //通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件                int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0);                switch (buttonId) {                case BUTTON_PREV_ID:                    Log.d(TAG , "上一首");                    Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();                    break;                case BUTTON_PALY_ID:                    String play_status = "";                    isPlay = !isPlay;                    if(isPlay){                        play_status = "开始播放";                    }else{                        play_status = "已暂停";                    }                    showButtonNotify();                    Log.d(TAG , play_status);                    Toast.makeText(getApplicationContext(), play_status, Toast.LENGTH_SHORT).show();                    break;                case BUTTON_NEXT_ID:                    Log.d(TAG , "下一首");                    Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();                    break;                default:                    break;                }            }        }    }
    /** 带按钮的通知栏点击广播接收 */    public void initButtonReceiver(){        bReceiver = new ButtonBroadcastReceiver();        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction(ACTION_BUTTON);        registerReceiver(bReceiver, intentFilter);    }

带进度条的通知

/** 显示带进度条通知栏 */    public void showProgressNotify() {        mBuilder.setContentTitle("等待下载")                .setContentText("进度:")                .setTicker("开始下载");// 通知首次出现在通知栏,带上升动画效果的        if(indeterminate){            //不确定进度的            mBuilder.setProgress(0, 0, true);        }else{            //确定进度的            mBuilder.setProgress(100, progress, false); // 这个方法是显示进度条  设置为true就是不确定的那种进度条效果        }        mNotificationManager.notify(notifyId, mBuilder.build());    }
/** 显示自定义的带进度条通知栏 */    private void showCustomProgressNotify(String status) {        RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_progress);        mRemoteViews.setImageViewResource(R.id.custom_progress_icon, R.drawable.icon);        mRemoteViews.setTextViewText(R.id.tv_custom_progress_title, "今日头条");        mRemoteViews.setTextViewText(R.id.tv_custom_progress_status, status);        if(progress >= 100 || downloadThread == null){            mRemoteViews.setProgressBar(R.id.custom_progressbar, 0, 0, false);            mRemoteViews.setViewVisibility(R.id.custom_progressbar, View.GONE);        }else{            mRemoteViews.setProgressBar(R.id.custom_progressbar, 100, progress, false);            mRemoteViews.setViewVisibility(R.id.custom_progressbar, View.VISIBLE);        }        mBuilder.setContent(mRemoteViews)                .setContentIntent(getDefalutIntent(0))                .setTicker("头条更新");        Notification nitify = mBuilder.build();        nitify.contentView = mRemoteViews;        mNotificationManager.notify(notifyId, nitify);    }

短信的发送和拦截
发送并监听发送是否成功
权限

<uses-permission android:name="android.permission.SEND_SMS"/>
Intent intent = new Intent("SENT_SMS_ACTION");//此处就用到 PendingIntent.getBroadcast 的方式//短信发送完毕后 会触发该意图PendingIntent pi  = PendingIntent.getBroadcast(AsenActivity.this, 0, intent, 0);SmsManager smsManager = SmsManager.getDefault();List<String> divideSms = smsManager.divideMessage( etSmsContent.getText().toString().trim());for (String smsContent : divideSms) {                    smsManager.sendTextMessage(etSmsPhone.getText().toString().trim(), null,smsContent, pi, null);}

还要写一个广播接受者 并注册关联

class SendSmsReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            if (getResultCode() == RESULT_OK) {                Toast.makeText(context, "sendsms success", Toast.LENGTH_SHORT).show();            }else {                Toast.makeText(context, "sendsms fail", Toast.LENGTH_SHORT).show();            }        }    }IntentFilter senderFilter = new IntentFilter();senderFilter.addAction("SENT_SMS_ACTION");sendSmsReceiver = new SendSmsReceiver();registerReceiver(sendSmsReceiver, senderFilter);

短信的拦截
权限

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

短信拦截的广播接收者 并注册关联相关 ACTION

class MessageReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {    Bundle bundle = intent.getExtras();    Object[] pdus = (Object[]) bundle.get("pdus");//接收短信消息    SmsMessage[] messages = new SmsMessage[pdus.length];    for (int i = 0; i < messages.length; i++) {        messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);    }    String address = messages[0].getOriginatingAddress();    //获取发送方号码    String fullMessage = "";    for (SmsMessage smsMessage : messages) {        fullMessage += smsMessage.getMessageBody();//获取短信内容    }    tvFromPhone.setText(address);    tvFromContent.setText(fullMessage);    abortBroadcast();    }}IntentFilter receiveSmsFilter  = new IntentFilter();        receiveSmsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");        receiveSmsFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);messageReceiver = new MessageReceiver();registerReceiver(messageReceiver, receiveSmsFilter);

不过 我的手机测试 并没有阻断该系统广播 虽然接收到了
通过静态注册方法 也是如此

 <receiver  android:name="com.asen.demo.MessageAbortReceiver" > <intent-filter android:priority="2147483647">  <action android:name="android.provider.Telephony.SMS_RECEIVED"/>  </intent-filter> </receiver>

android:priority=”2147483647“ 也没有拦阻系统接收

于是检索到 关于广播的优先级的文章 广播的优先级

这篇文章给我的收获 :
优先级别声明在intent-filter 元素的 android:priority 属性中,数越大优先级别越高,最大值是2147483647;优先级别也可以调用IntentFilter对象的setPriority()进行设置。

A,接收无序广播的接收器接收到广播的顺序是有序的,
B,接收无序广播的接收器也一样可以设置优先级的。

但几乎是同时到达

静态接收器优先级低于动态接收器,也就是说,无论多么高级别的静态接收器和多么低级别的动态接收器都接收同一广播,永远都是动态接收器先接收到!同等优先级的动态接收器,先注册的先接收。

有些广播必须是动态注册的receiver才能收到
比如ACTION_SCREEN_ON,当屏幕被点亮的时候系统发送此广播,如果你尝试在manifest中注册receiver来接收,那么会失败,这是为什么呢?他们在Intent中都设置了Intent.FLAG_RECEIVER_REGISTERED_ONLY,所以如果要接收,必须动态注册广播接收器,ACTION_SCREEN_OFF也是如此。

但是知道这些依然无用 我看到的现象 短信接收 这个系统广播 并不是有序的 而是无序的
于是又检索到这篇文章 比较好 里面的代码亲测有效 短信拦截适配

收获主要是
4.4及其以后系统,只能设置一个 默认的SMS短信app ,但短信到达,首先会通知这个app,并且只有这个app有对 短信数据库的修改权限 和 短信的发送权限

并且短信广播,不再是有序广播 ,也就是App没有办法拦截这个广播,所 有app都快接收到短信到达的广播通知 ,但是 只有默认SMS短信app可以修改短信记录
但是!不排除有些操作系统,例如小米会修改这个机制!

另外修改短信默认设置

请求用户把你的应用设置成默认短信应用以便进行短信还原(你必须作为默认短信应用才可以写入数据到SMS Provider中)。

Intent intent = new Intent(context, Sms.Intents.ACTION_CHANGE_DEFAULT);intent.putExtra(Sms.Intents.EXTRA_PACKAGE_NAME, context.getPackageName());startActivity(intent);

可以以此类推 其他默认设置的写法

0 0
原创粉丝点击