选中复选框后如何发送通知?

时间:2016-06-02 01:48:07

标签: android android-notifications

public class Settings extends AppCompatActivity {

CheckBox cb1;

NotificationManager manager;
Notification myNotication;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    cb1=(CheckBox) findViewById(R.id.notificationchk);


    manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// anything here and above seems ok(no error)

    cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)//"this" taskstackbuilder cannot be applied to oncheckedlistener
                    .Builder(mContext)//the mcontext is not working
                    .setContentTitle("New mail from ")
                    .setContentText("i")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .build();Intent resultIntent = new Intent(this, firstpage.class);//everything inside bracket underlined red
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);//"this" taskstackbuilder cannot be applied to oncheckedlistener

        stackBuilder.addParentStack(Settings.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);//cannot resolve symbol mBuilder 
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.notify(mId, mBuilder.build());//cannot resolve symbol mID,mBuilder 

    }//all errors marked


});//basically this,mbuilder,mID,mContext problem

我是java和android app deveopement的新手。我已经在互联网上搜索了几个小时来获取通知和复选框一起工作并最终失败。 谢谢你的精彩回答:D

2 个答案:

答案 0 :(得分:1)

您正在构建通知。但是您还没有通知NotifcationManager。查看official docs示例,也许您错过了这样的内容?

NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());

答案 1 :(得分:1)

将其更改为Settings.this

使用mcontext删除第二个构建器。

与此内部意图相同。将其更改为Settings.this

TaskStackBuilder.create(this)相同,将其更改为TaskStackBuilder.create(Settings.this)

将此mBuilder.setContentIntent(resultPendingIntent)更改为builder.setContentIntent(resultPendingIntent)

mNotificationManager.notify(mId, mBuilder.build())更改为mNotificationManager.notify(1, builder.build())