通知栏构建和取消的基本认识

思路图

 

MainActivity.class

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    NotificationManager manager;
    int notification_ID = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         findViewById(R.id.send_message).setOnClickListener(this);
         findViewById(R.id.cancel_message).setOnClickListener(this);
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  //取得通知控制类


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send_message:{
                send_message_method();
                break;
            }
            case R.id.cancel_message:{
                cancel_message_method();
                break;
            }
        }
    }

    //构建发送通知方法
    private void cancel_message_method() {
        manager.cancel(notification_ID);
    }
    //取消通知栏
    private void send_message_method() {

        Intent itent = new Intent(this,MainActivity.class);
        PendingIntent pitent = PendingIntent.getActivity(this,0,itent,0);
        //构建Notification的builder构建器
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);     //设置图标
        builder.setTicker("你好,世界!");   //设置手机状态栏提示信息
        builder.setWhen(System.currentTimeMillis());    // 设置时间
        builder.setContentTitle("世界游戏之标题");     //设置标题
        builder.setContentText("鹅鹅鹅,曲项向天歌!");   //设置通知内容

        builder.setContentIntent(pitent); //设置点击后的意图
//        builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置提示指示灯
//        builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示声音
//        builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置提示震动
        builder.setDefaults(Notification.DEFAULT_ALL);  //设置全部都有
        Notification notification =  builder.build();//4.1以上
        manager.notify(notification_ID,notification);

    }
}

 注意设置Defaults时候的权限。振动,声音权限。

<uses-permission android:name="ANDROID.PERMISSION.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE"/>

 

posted on 2015-10-17 18:06  纸玫瑰  阅读(157)  评论(0编辑  收藏  举报

导航