Я работаю над приложением, которое показывает пользователю в строке состояния уведомления. Пользователь может включать и выключать уведомления и звук уведомлений с помощью 2 переключателей. Я запустил приложение и попытался включить уведомление, и оно упало. Трассировка стека указана в строке 60 (я пометил ее так, чтобы вы могли легко ее найти): Попытка вызвать виртуальный метод 'void android .app.NotificationManager.notify (int, android .app.Notification)' на нулевую ссылку на объект
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Settings extends AppCompatActivity {
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
NotificationManager manager;
Notification myNotication;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleswitch1.setChecked(false);
simpleswitch2.setChecked(false);
simpleswitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){{
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext...");
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);//THE ERROR LED HERE
}
}
simpleswitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
notification.defaults |= Notification.DEFAULT_SOUND;
}}
});}});}}