码迷,mamicode.com
首页 > 其他好文 > 详细

Notification使用涉猎,让你快速使用,拿来就用!

时间:2015-07-10 22:26:04      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:android   通知   服务器   安卓   

转载请注明出处王亟亟的大牛之路
通知Notification是我们的手机一个使用非常频繁的告诉用户一些信息的载体。安卓的推送信可以利用打不死的Service 或者broadcastReceiver去抓服务器的内容来推送给用户,相比之下iOS个人看起来就觉得很麻烦,需要https服务器去推,当然也有公用的,只是不太喜欢。
Android
技术分享
iOS
技术分享
实现方式不同,反正就是这么一个东西

废话不多说,上图!
技术分享
自定义Notification
技术分享

分类
1,普通Notification
技术分享
1.内容标题

2.大图标

3.内容

4.内容附加信息

5.小图标

6.时间

2>大布局Notification
技术分享
上图为NotificationCompat.InboxStyle 类型

大布局notification是在android4.1以后才增加的,大布局notification与小布局notification只在‘7‘部分有区别,其它部分都一致。大布局notification只有在所有notification的最上面时才会显示大布局,其它情况下显示小布局。你也可以用手指将其扩展为大布局(前提是它是大布局)

如下图:
技术分享
上图为NotificationCompat.BigTextStyle
技术分享
上图为NotificationCompat.BigPictureStyle
3>自定义布局notification
上面那张Music就是一种自定义的Notification

项目目录结构:
技术分享

MainActivity:

public class MainActivity extends ActionBarActivity implements View.OnClickListener{
    private Button btn_show;//显示通知栏
    private Button btn_show_progress;//显示带进度条通知栏
    private Button btn_show_cz;//显示常驻通知栏
    private Button btn_clear;//清除指定通知
    private Button btn_clear_all;//清除所有通知
    private Button btn_show_custom;//显示自定义通知栏
    /** 点击跳转到指定的界面 */
    private Button btn_show_intent_act;//显示通知,点击跳转到指定Activity
    /** Notification构造器 */
    NotificationCompat.Builder mBuilder;
    /** Notification的ID */
    int notifyId = 100;

    /** Notification管理 */
    public NotificationManager mNotificationManager;

    /**
     * 初始化要用到的系统服务
     */
    private void initService() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    /**
     * 清除当前创建的通知栏
     */
    public void clearNotify(int notifyId){
        mNotificationManager.cancel(notifyId);//删除一个特定的通知ID对应的通知
//      mNotification.cancel(getResources().getString(R.string.app_name));
    }

    /**
     * 清除所有通知栏
     * */
    public void clearAllNotify() {
        mNotificationManager.cancelAll();// 删除你发的所有通知
    }

    /**
     * @获取默认的pendingIntent,为了防止2.3及以下版本报错
     * @flags属性:
     * 在顶部常驻:Notification.FLAG_ONGOING_EVENT
     * 点击去除: Notification.FLAG_AUTO_CANCEL
     */
    public PendingIntent getDefalutIntent(int flags){
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);
        return pendingIntent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initService();
        initView();
        initNotify();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        btn_show = (Button)findViewById(R.id.btn_show);
        btn_show_progress = (Button)findViewById(R.id.btn_show_progress);
        btn_show_cz = (Button)findViewById(R.id.btn_show_cz);
        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_clear_all = (Button)findViewById(R.id.btn_clear_all);
        btn_show_custom = (Button)findViewById(R.id.btn_show_custom);
        btn_show_intent_act = (Button)findViewById(R.id.btn_show_intent_act);
        btn_show.setOnClickListener(this);
        btn_show_progress.setOnClickListener(this);
        btn_show_cz.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        btn_clear_all.setOnClickListener(this);
        btn_show_custom.setOnClickListener(this);
        btn_show_intent_act.setOnClickListener(this);
    }

    /** 初始化通知栏 */
    private void initNotify(){
        mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("测试标题")
                .setContentText("测试内容")
                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
//              .setNumber(number)//显示数量
                .setTicker("测试通知来啦")//通知首次出现在通知栏,带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示
                .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
                        //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                .setSmallIcon(R.mipmap.ic_launcher);
    }
    /** 显示通知栏 */
    public void showNotify(){
        mBuilder.setContentTitle("测试标题")
                .setContentText("测试内容")
//              .setNumber(number)//显示数量
                .setTicker("测试通知来啦");//通知首次出现在通知栏,带上升动画效果的
        mNotificationManager.notify(notifyId, mBuilder.build());
//      mNotification.notify(getResources().getString(R.string.app_name), notiId, mBuilder.build());
    }

    /** 显示常驻通知栏 */
    public void showCzNotify(){
//      Notification mNotification = new Notification();//为了兼容问题,不用该方法,所以都采用BUILD方式建立
//      Notification mNotification  = new Notification.Builder(this).getNotification();//这种方式已经过时
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//      //PendingIntent 跳转动作
        PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, getIntent(), 0);
        mBuilder.setSmallIcon(R.drawable.ic_launcher)
                .setTicker("常驻通知来了")
                .setContentTitle("常驻测试")
                .setContentText("使用cancel()方法才可以把我去掉哦")
                .setContentIntent(pendingIntent);
        Notification mNotification = mBuilder.build();
        //设置通知  消息  图标
        mNotification.icon = R.drawable.ic_launcher;
        //在通知栏上点击此通知后自动清除此通知
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;//FLAG_ONGOING_EVENT 在顶部常驻,可以调用下面的清除方法去除  FLAG_AUTO_CANCEL  点击和清理可以去调
        //设置显示通知时的默认的发声、震动、Light效果
        mNotification.defaults = Notification.DEFAULT_VIBRATE;
        //设置发出消息的内容
        mNotification.tickerText = "常驻!通知来了";
        //设置发出通知的时间
        mNotification.when=System.currentTimeMillis();
//      mNotification.flags = Notification.FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知
//      mNotification.setLatestEventInfo(this, "常驻测试", "使用cancel()方法才可以把我去掉哦", null); //设置详细的信息  ,这个方法现在已经不用了
        mNotificationManager.notify(notifyId, mNotification);
    }

    /** 显示通知栏点击跳转到指定Activity */
    public void showIntentActivityNotify(){
        // Notification.FLAG_ONGOING_EVENT --设置常驻 Flag;Notification.FLAG_AUTO_CANCEL 通知栏上点击此通知后自动清除此通知
//      notification.flags = Notification.FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知
        mBuilder.setAutoCancel(true)//点击后让通知将消失
                .setContentTitle("测试标题")
                .setContentText("点击跳转")
                .setTicker("点我");
        //点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        mNotificationManager.notify(notifyId, mBuilder.build());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_show:
                showNotify();
                break;
            case R.id.btn_show_cz:
                showCzNotify();
                break;
            case R.id.btn_clear:
                clearNotify(notifyId);
                break;
            case R.id.btn_clear_all:
                clearAllNotify();
                break;
            case R.id.btn_show_intent_act:
                showIntentActivityNotify();
                break;
            case R.id.btn_show_progress:
                startActivity(new Intent(this, ProgressAcitivty.class));
                break;
            case R.id.btn_show_custom:
                startActivity(new Intent(this, CustomActivity.class));
                break;
            default:
                break;
        }
    }
}

主Activity的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">
    <Button
        android:id="@+id/btn_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示通知栏" />
    <Button
        android:id="@+id/btn_show_cz"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示常驻通知栏" />
    <Button
        android:id="@+id/btn_show_intent_act"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示通知,点击跳转到指定Activity"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <Button
        android:id="@+id/btn_clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清除指定通知"
        android:layout_alignBaseline="@+id/btn_clear_all"
        android:layout_alignBottom="@+id/btn_clear_all"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/btn_clear_all"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清除所有通知"
        android:layout_below="@+id/btn_show_intent_act"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:id="@+id/btn_show_custom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示自定义通知栏"
        android:layout_below="@+id/btn_show_progress"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <Button
        android:id="@+id/btn_show_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示带进度条通知栏"
        android:layout_below="@+id/btn_show_intent_act"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
       />
</LinearLayout>

兼容用的工具类

public class BaseTools {
    /**
     * 获取当前应用版本号
     * @param context
     * @return version
     * @throws Exception
     */
    public static String getAppVersion(Context context) throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),0);
        String versionName = packInfo.versionName;
        return versionName;
    }

    /**
     * 获取当前系统SDK版本号
     */
    public static int getSystemVersion(){
        /*获取当前系统的android版本号*/
        int version= android.os.Build.VERSION.SDK_INT;
        return version;
    }
}

自定义Notification

public class CustomActivity extends ActionBarActivity implements OnClickListener{
    /** Notification管理 */
    public NotificationManager mNotificationManager;

    /** TAG */
    private final static String TAG = "CustomActivity";
    /** 按钮:显示自定义通知 */
    private Button btn_show_custom;
    /** 按钮:显示自定义带按钮的通知 */
    private Button btn_show_custom_button;
    /** Notification 的ID */
    int notifyId = 101;
    /** NotificationCompat 构造器*/
    Builder mBuilder;
    /** 是否在播放*/
    public boolean isPlay = false;
    /** 通知栏按钮广播 */
    public ButtonBroadcastReceiver bReceiver;
    /** 通知栏按钮点击事件对应的ACTION */
    public final static String ACTION_BUTTON = "com.notifications.intent.action.ButtonClick";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom);
        initService();
        initView();
        initButtonReceiver();
    }
    /**
     * 初始化要用到的系统服务
     */
    private void initService() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private void initView() {
        btn_show_custom = (Button) findViewById(R.id.btn_show_custom);
        btn_show_custom.setOnClickListener(this);
        btn_show_custom_button = (Button) findViewById(R.id.btn_show_custom_button);
        btn_show_custom_button.setOnClickListener(this);
    }

    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, "title");
        view_custom.setTextViewText(R.id.tv_custom_content, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//      view_custom.setTextViewText(R.id.tv_custom_time, String.valueOf(System.currentTimeMillis()));
        //设置显示
//      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("new")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(false)//不是正在进行的   true为正在进行  效果和.flag一样
                .setSmallIcon(R.drawable.icon);
//      mNotificationManager.notify(notifyId, mBuilder.build());
        Notification notify = mBuilder.build();
        notify.contentView = view_custom;
//      Notification notify = new Notification();
//      notify.icon = R.drawable.icon;
//      notify.contentView = view_custom;
//      notify.contentIntent = getDefalutIntent(Notification.FLAG_AUTO_CANCEL);
        mNotificationManager.notify(notifyId, notify);
    }

    /**
     * 带按钮的通知栏
     */
    public void showButtonNotify(){
        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, "music");
        mRemoteViews.setTextViewText(R.id.tv_custom_song_name, "ok");
        //如果版本号低于(3。0),那么不显示按钮
        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("running")
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(R.drawable.sing_icon);
        Notification notify = mBuilder.build();
        notify.flags = Notification.FLAG_ONGOING_EVENT;
        //会报错,还在找解决思路
//      notify.contentView = mRemoteViews;
//      notify.contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
        mNotificationManager.notify(100, notify);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_show_custom:
            shwoNotify();
            break;
        case R.id.btn_show_custom_button:
            showButtonNotify();
            break;
        default:
            break;
        }
    }

    /** 带按钮的通知栏点击广播接收 */
    public void initButtonReceiver(){
        bReceiver = new ButtonBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BUTTON);
        registerReceiver(bReceiver, intentFilter);
    }

    public final static String INTENT_BUTTONID_TAG = "ButtonId";
    /** 上一首 按钮点击 ID */
    public final static int BUTTON_PREV_ID = 1;
    /** 播放/暂停 按钮点击 ID */
    public final static int BUTTON_PALY_ID = 2;
    /** 下一首 按钮点击 ID */
    public final static int BUTTON_NEXT_ID = 3;
    /**
     *   广播监听按钮点击时间 
     */
    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 , "up");
                    Toast.makeText(getApplicationContext(), "up", Toast.LENGTH_SHORT).show();
                    break;
                case BUTTON_PALY_ID:
                    String play_status = "";
                    isPlay = !isPlay;
                    if(isPlay){
                        play_status = "go";
                    }else{
                        play_status = "stop";
                    }
                    showButtonNotify();
                    Log.d(TAG , play_status);
                    Toast.makeText(getApplicationContext(), play_status, Toast.LENGTH_SHORT).show();
                    break;
                case BUTTON_NEXT_ID:
                    Log.d(TAG , "next");
                    Toast.makeText(getApplicationContext(), "next", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if(bReceiver != null){
            unregisterReceiver(bReceiver);
        }
        super.onDestroy();
    }
    /**
     * @获取默认的pendingIntent,为了防止2.3及以下版本报错
     * @flags属性:
     * 在顶部常驻:Notification.FLAG_ONGOING_EVENT
     * 点击去除: Notification.FLAG_AUTO_CANCEL
     */
    public PendingIntent getDefalutIntent(int flags){
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);
        return pendingIntent;
    }
}

带进度条Notification

public class ProgressAcitivty extends ActionBarActivity implements OnClickListener {
    /** Notification管理 */
    public NotificationManager mNotificationManager;

    private Button btn_show_progress;
    private Button btn_show_un_progress;
    private Button btn_show_custom_progress;
    /** Notification的ID */
    int notifyId = 102;
    /** Notification的进度条数值 */
    int progress = 0;
    Builder mBuilder;
    Button btn_download_start;
    Button btn_download_pause;
    Button btn_download_cancel;
    /** 下载线程是否暂停 */
    public boolean isPause = false;
    /** 通知栏内是否是自定义的 */
    public boolean isCustom = false;
    DownloadThread downloadThread;
    /** true:为不确定样式的   false:确定样式*/
    public Boolean indeterminate = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.progress);
        initService();
        initView();
        initNotify();
    }
    /**
     * 初始化要用到的系统服务
     */
    private void initService() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private void initView() {
        btn_show_progress = (Button) findViewById(R.id.btn_show_progress);
        btn_show_un_progress = (Button) findViewById(R.id.btn_show_un_progress);
        btn_show_custom_progress = (Button) findViewById(R.id.btn_show_custom_progress);
        btn_download_start = (Button) findViewById(R.id.btn_download_start);
        btn_download_pause = (Button) findViewById(R.id.btn_download_pause);
        btn_download_cancel = (Button) findViewById(R.id.btn_download_cancel);
        btn_show_progress.setOnClickListener(this);
        btn_show_un_progress.setOnClickListener(this);
        btn_show_custom_progress.setOnClickListener(this);
        btn_download_start.setOnClickListener(this);
        btn_download_pause.setOnClickListener(this);
        btn_download_cancel.setOnClickListener(this);
    }

    /** 初始化通知栏 */
    private void initNotify() {
        mBuilder = new Builder(this);
        mBuilder.setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示
                .setContentIntent(getDefalutIntent(0))
                // .setNumber(number)//显示数量
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                // .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)// ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE)// 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:
                // Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 //
                // requires VIBRATE permission
                .setSmallIcon(R.drawable.icon);
    }

    /** 显示带进度条通知栏 */
    public void showProgressNotify() {
        mBuilder.setContentTitle("wait")
                .setContentText("process:")
                .setTicker("start");// 通知首次出现在通知栏,带上升动画效果的
        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, "news");
        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("new nes");
        Notification nitify = mBuilder.build();
        nitify.contentView = mRemoteViews;
        mNotificationManager.notify(notifyId, nitify);
    }

    /** 开始下载 */
    public void startDownloadNotify() {
        isPause = false;
        if (downloadThread != null && downloadThread.isAlive()) {
//          downloadThread.start();
        }else{
            downloadThread = new DownloadThread();
            downloadThread.start();
        }
    }

    /** 暂停下载 */
    public void pauseDownloadNotify() {
        isPause = true;
        if(!isCustom){
            mBuilder.setContentTitle("already stop");
            setNotify(progress);
        }else{
            showCustomProgressNotify("already stop");
        }
    }

    /** 取消下载 */
    public void stopDownloadNotify() {
        if (downloadThread != null) {
            downloadThread.interrupt();
        }
        downloadThread = null;
        if(!isCustom){
            mBuilder.setContentTitle("Cancel").setProgress(0, 0, false);
            mNotificationManager.notify(notifyId, mBuilder.build());
        }else{
            showCustomProgressNotify("Cancel");
        }
    }

    /** 设置下载进度 */
    public void setNotify(int progress) {
        mBuilder.setProgress(100, progress, false); // 这个方法是显示进度条
        mNotificationManager.notify(notifyId, mBuilder.build());
    }

    /**
     * 下载线程
     */
    class DownloadThread extends Thread {

        @Override
        public void run() {
            int now_progress = 0;
            // Do the "lengthy" operation 20 times
            while (now_progress <= 100) {
                // Sets the progress indicator to a max value, the
                // current completion percentage, and "determinate"
                if(downloadThread == null){
                    break;
                }
                if (!isPause) {
                    progress = now_progress;
                    if(!isCustom){
                        mBuilder.setContentTitle("running");
                        if(!indeterminate){
                            setNotify(progress);
                        }
                    }else{
                        showCustomProgressNotify("running");
                    }
                    now_progress += 10;
                }
                try {
                    // Sleep for 1 seconds
                    Thread.sleep(1 * 1000);
                } catch (InterruptedException e) {
                }
            }
            // When the loop is finished, updates the notification
            if(downloadThread != null){
                if(!isCustom){
                    mBuilder.setContentText("finish")
                    // Removes the progress bar
                    .setProgress(0, 0, false);
                    mNotificationManager.notify(notifyId, mBuilder.build());
                }else{
                    showCustomProgressNotify("finish");
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_show_progress:
            downloadThread = null;
            isCustom = false;
            indeterminate = false;
            showProgressNotify();
            break;
        case R.id.btn_show_un_progress:
            downloadThread = null;
            isCustom = false;
            indeterminate = true;
            showProgressNotify();
            break;
        case R.id.btn_show_custom_progress:
            downloadThread = null;
            isCustom = true;
            indeterminate = false;
            showCustomProgressNotify("wait..");
            break;
        case R.id.btn_download_start:
            startDownloadNotify();
            break;
        case R.id.btn_download_pause:
            pauseDownloadNotify();
            break;
        case R.id.btn_download_cancel:
            stopDownloadNotify();
            break;
        default:
            break;
        }
    }
    /**
     * @获取默认的pendingIntent,为了防止2.3及以下版本报错
     * @flags属性:
     * 在顶部常驻:Notification.FLAG_ONGOING_EVENT
     * 点击去除: Notification.FLAG_AUTO_CANCEL
     */
    public PendingIntent getDefalutIntent(int flags){
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);
        return pendingIntent;
    }
}

源码:http://yunpan.cn/ccZH7AbmiSEed 访问密码 4f2e

具体的内容看源码就一目了然了,有问题欢迎+Q 452270579交流,谢谢!

版权声明:本文为博主原创文章,未经博主允许不得转载。

Notification使用涉猎,让你快速使用,拿来就用!

标签:android   通知   服务器   安卓   

原文地址:http://blog.csdn.net/ddwhan0123/article/details/46833745

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!