这是完整的代码。
import ...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void notify(View view) {
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_LONG).show();
//shows the toast "Clicked"
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.small)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
我做错了什么? 这不会创建任何通知。我是一个相当新的android并且自己学习。这是我第一次被困了很长时间。我到处搜索,所有的资源告诉我我已经做过的事情。 请帮忙。
答案 0 :(得分:1)
找到答案。
我的手机是奥利奥。我不得不使用通知渠道。这里提到的答案在具有较低版本的模拟器上运行得非常好。
使用[GitHub](https://github.com/tutsplus/android-o-how-to-use-notification-channels)作为参考。
谢谢大家的回答。
答案 1 :(得分:0)
您没有调用通知功能:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notify(); //Call here
}
public void notify() //View is not used
{
// Rest of the code is same
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_LONG).show();
//显示吐司"点击"
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
如果您使用
public void notify(View view) //View is required
{
然后调用:notify(null);
否则只需要调用:notify();
会抛出以下异常 - >
java.lang.IllegalMonitorStateException:在notify()之前没有被线程锁定的对象