java按下按钮并显示通知
我在xml中有一个按钮,当它被单击时,下面的代码应该显示一个通知位,它没有运行,并给出一个错误(notification.Builder(new View.OnClickListener(){})是未定义的) 有人告诉我有什么问题吗
主要活动。爪哇
package com.example.auto;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b =(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,
0, intent, 0);
Notification mNotification = new Notification.Builder(this)
.setContentTitle("New Post!")
.setContentText("Here's an awesome update for you!")
.setContentIntent(pIntent)
.addAction(0, "View", pIntent)
.addAction(0, "Remind", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotification);
}
});
}
}
# 1 楼答案
试试这个:)
# 2 楼答案
构造函数需要一个
Context
,而OnClickListener
是noContext
更改此项:
致:
# 3 楼答案
您不能将“this”用作上下文,因为使用它您引用的是新的OnClickListener,而不是您的活动
要获取封闭活动的上下文,必须使用MainActivity。这: