創建notification的方法



說明:
根據項目選擇的基礎sdk,選擇不同的創建Notification的方法
1 在android sdk 3.0 之前直接通過 new Notification的方法直接創建通知對象

2 在android sdk 3.0 是通過Notification.Builer的方法間接配置Notification的屬性和創建Notification的功能

3 在android sdk4.0以上 是通過android-support-v4.jar 包中的NotificationCompat.Builder類,進行配置創建Notification對象


下面是一個實例,用NotificationCompat.Builder的方式創建Notification

 

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("My notification")
                .setContentText("Hello World!");
        
        //Notification.Builder builder=new Notification.Builder(this);
         
        mBuilder.setAutoCancel(true);
        mBuilder.setLights(Color.BLUE, 500, 500);
        long[] pattern = {500,500,500,500,500,500};
        mBuilder.setVibrate(pattern);
        
        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.messagevoice);
        mBuilder.setSound(sound);
        //mBuilder.setSound(sound);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, MessageShowActivity.class);

        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        //stackBuilder.addParentStack(MessageShowActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(this, 0, new Intent(this,MessageShowActivity.class), 0);
        
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.
        mNotificationManager.notify(12, mBuilder.build());


發佈了24 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章