我使用 FirebaseMessagingService 和 SharedPreferences。
检查开关时,我尝试使用 Firebase 获取通知消息。
所以我做了这样的代码。
public class MainActivity extends AppCompatActivity {
Switch toggleSwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleSwitch = findViewById(R.id.toggleSwitch);
SharedPreferences sharedPreferences = getSharedPreferences("state", MODE_PRIVATE);
toggleSwitch.setChecked(sharedPreferences.getBoolean("state", true));
toggleSwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (toggleSwitch.isChecked()) {
Toast.makeText(getApplicationContext(), "Switch On", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = getSharedPreferences("state", MODE_PRIVATE).edit();
editor.putBoolean("state", true);
editor.apply();
toggleSwitch.setChecked(true);
} else {
Toast.makeText(getApplicationContext(), "Switch Off", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = getSharedPreferences("state", MODE_PRIVATE).edit();
editor.putBoolean("state", false);
editor.apply();
toggleSwitch.setChecked(false);
}
}
});
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
SharedPreferences sharedPreferences = getSharedPreferences("state", MODE_PRIVATE);
if (sharedPreferences.getBoolean("state", true)) {
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
}
}
private void sendNotification(String messageTitle, String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = getString(R.string.default_notification_channel_name);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
此代码在应用程序运行时正常工作。
但是,当您关闭应用程序时,即使开关关闭,也会出现通知消息。
FirebaseMessagingService 不能由 SharedPreferences 控制吗?
还是我做错了什么?
请帮帮我。