I have an application where I have a floating widget running as Service.
But whenever I close the app, the widget (service) is restarted. this doesn't happen on API 26+
manifest.xml
<service
android:name=".widget"
android:enabled="true"
android:exported="false"/>
widget.java
public class widget extends Service {
private WindowManager mWindowManager;
private View view;
static boolean expanded = false;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
setTheme(R.style.AppTheme);
view = LayoutInflater.from(this).inflate(R.layout.widget, null);
int layoutFlag = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ? TYPE_APPLICATION_OVERLAY : TYPE_PHONE;
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
layoutFlag,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER | Gravity.START;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(view, params);
}
@Override
public void onDestroy() {
super.onDestroy();
if (view != null) {
mWindowManager.removeView(view);
}
}
MainActivity.java
intent = new Intent(MainActivity.this, widget.class);
startService(intent);
Note: Permission is granted
So this works fine on any device above or equal to API 26
and it still works on devices below api 26 but it has that restarting issue, any idea what might be causing that and how can I deal with it?
also notice the only thing that differs the 2 versions in code is this part
int layoutFlag = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ? TYPE_APPLICATION_OVERLAY : TYPE_PHONE;
question from:
https://stackoverflow.com/questions/65877665/floating-widget-restarting-issue-in-android-pre-api-26-api-26 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…