Я делаю простое приложение у которого есть две кнопки: запустить сервис и остановить сервис.
У приложения есть такие состояния:
- При нажатии на кнопку Start Service запускается Foreground Service и отображается нотификация.
- При нажатии на кнопку Stop Service - сервис.
- При сворачивании приложения, должно отображаться Heads-Up(!) уведомление.
Сейчас, при нажатии на Start Service сразу отображается Heads-Up уведомление. Но я хочу что бы Heads-Up уведомление отображалось только тогда, когда приложение уходит в беграунд.
Я создал флаг isFirstServiceLaunch, который говорит, менять Importance канала или нет. Но при этом моя программа не реагирует на эти изменения.
Пожалуйста, можете помочь советом или сказать что я делаю не так? Спасибо!
MainActivity.java
public class MainActivity extends AppCompatActivity {
private CallingIndicatorService mService;
private boolean mBounded;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
CallingIndicatorService.LocalBinder mLocalBinder = (CallingIndicatorService.LocalBinder)service;
mService = mLocalBinder.getServerInstance();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
};
@Override
protected void onStop() {
super.onStop();
// Show Heads Up notification HERE
mService.showNotification();
};
public void startService(View view){
Intent intent = new Intent(this, CallingIndicatorService.class);
ContextCompat.startForegroundService(this, intent);
bindService(intent, mConnection, BIND_NOT_FOREGROUND);
}
public void stopService(View view) {
if(mBounded) {
unbindService(mConnection);
mBounded = false;
}
stopService(new Intent(this, CallingIndicatorService.class));
}
}
CallingIndicatorService.java
public class CallingIndicatorService extends Service {
private static final int UNIQUE_NOTIFICATION_ID = 1002;
private NotificationManager mNotificationManager;
private boolean isFirstServiceLaunch = false;
private IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public CallingIndicatorService getServerInstance() {
return CallingIndicatorService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(UNIQUE_NOTIFICATION_ID, createNotification());
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mNotificationManager = null;
mBinder = null;
}
@Override
public void onTaskRemoved(Intent rootIntent){
stopSelf();
super.onTaskRemoved(rootIntent);
}
private Notification createNotification() {
String name = "my_package_channel";
String id = "my_package_channel_1";
String description = "my_package_first_channel";
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = !isFirstServiceLaunch ? NotificationManager.IMPORTANCE_NONE : NotificationManager.IMPORTANCE_HIGH;
Log.d("test_t", "importance: " + importance);
NotificationChannel mChannel = mNotificationManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setLightColor(Color.GREEN);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(this, id);
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle("Title")
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(this.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker("Title ticker")
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
} else {
builder = new NotificationCompat.Builder(this);
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle("Title 1") // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(this.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker("Title ticker 1")
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(
!isFirstServiceLaunch ? Notification.PRIORITY_DEFAULT : Notification.PRIORITY_HIGH
);
}
return builder.build();
}
public void showNotification() {
isFirstServiceLaunch = true;
mNotificationManager.notify(UNIQUE_NOTIFICATION_ID, createNotification());
}
}