文章出處

Android通知(Notification)詳解,最近項目用到了安卓下的Notification,也就是通知。今天我們就通過一個列子來了解一下android下的Notification,首先是先看怎么使用Notification。

其實發送一個通知到通知欄特別簡單

 

private void showNotification(int id, String title, String data) {Intent broadcastIntent = new Intent(this, NotificationReceiver.class); // 設置一個廣播接收者去打開要做的事情PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);mBuilder.setContentTitle(title) // 設置通知標題.setContentText(data)   // 設置通知內容.setContentIntent(pendingIntent)    // 設置點擊通知消息的action.setSmallIcon(R.drawable.pushsmall) // 設置通知欄顯示的小圖標,國產手機一般不顯示,默認是用大圖標來代替.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) // 設置通知欄顯示的大圖標.setAutoCancel(true);   // 點擊通知消息后通知消息消失NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);notificationManager.notify(id, mBuilder.build());}


 

廣播接收者NotificationReceiver的代碼

 

public class NotificationReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        //判斷app進程是否存活        if (isAppAlive(context, "com.bandeng.temp")) {            Intent startIntent = new Intent(context, PushActivity.class);            startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            context.startActivity(startIntent);        } else {            Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.bandeng.temp");            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);            Intent detailIntent = new Intent(context, PushActivity.class);            Intent[] intents = {launchIntent, detailIntent};            context.startActivities(intents);        }    }    private boolean isAppAlive(Context context, String packageName) {        boolean isAppRunning = false;        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);        List list = am.getRunningTasks(100);        for (ActivityManager.RunningTaskInfo info : list) {            if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {                isAppRunning = true;                break;            }        }        return isAppRunning;    }}

 

看效果

 

\

 

 

關于通知欄消息我們需要注意一點,就是在android5.0之后setSmallIcon()設置小圖標,如果這個小圖標不是背景透明色,小圖標就會出現整個白色,上面演示的通知欄小圖標的背景是透明的,所以不會出現小白點。下面我就演示將小圖標設置成背景不是透明色的大圖標

小圖標設置為大圖標

 

mBuilder.setSmallIcon(R.drawable.ic_launcher)

 

看下面效果

 

\
 

其實在國產手機上一般是沒有問題的,因為國產手機的系統被修改過,一般用大圖標代替小圖標

 

看文倉www.92to.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。
歡迎轉載:http://www.kanwencang.com/bangong/20161220/74662.html

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()