Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

Floating widget restarting issue in Android pre - API 26 (> API 26)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...