问题描述
我使用FirebaseMessagingService和SharedPreferences。
所以我编写了这样的代码。
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",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,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控制吗?
还是我做错了什么?
请帮助我。
解决方法
您有两种类型的通知-“数据”和“通知”。如果您访问此网页:Handling Received Messages,您将看到,根据通知中收到的实际负载,您可以控制通知。
我将尝试在通知中仅发送“数据”有效负载,然后检查FirebaseMessagingService在不同情况下的工作方式:当应用程序在托盘中,何时应用程序被完全杀死等。
我希望在某些设备(主要是中国制造商)上,该应用被终止且未列入白名单时,您将不会在onMessageReceived
中收到回调,也将无法控制通知。