API 26中的服务

时间:2018-10-19 11:09:04

标签: java android android-studio exception service

代码

public class MainService extends JobIntentService {
WindowManager wm;
LayoutInflater li;
RelativeLayout ll;
View myview;
int NOTIFICATION_ID = 1;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    String CHANNEL_ID = "my_service";
    String CHANNEL_NAME = "My Background Service";
    if (Build.VERSION.SDK_INT >= 26) {
        // in APIs 26+ we should show a notifications
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setCategory(Notification.CATEGORY_SERVICE).setPriority(PRIORITY_MIN).build();

        startForeground(NOTIFICATION_ID, notification);
    }

    wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    ll = new RelativeLayout(this);
    ll.setBackgroundColor(Color.RED);
    LinearLayout.LayoutParams layoutParameteres = new LinearLayout.LayoutParams(
            50, 500);
    ll.setBackgroundColor(Color.argb(66,255,0,0));
    ll.setLayoutParams(layoutParameteres);

    canDrawOnScreen();

    final WindowManager.LayoutParams parameters = new WindowManager.LayoutParams(
            50, 500, WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);
    parameters.gravity = Gravity.RIGHT | Gravity.CENTER;
    parameters.x = 0;
    parameters.y = 0;

    wm.addView(ll, parameters);
    WindowManager.LayoutParams updatedParameters = parameters;

    ll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Intent intent = new Intent(MainService.this,UsersService.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startService(intent);

        }
    });

}

@Override
public void onDestroy() {
    super.onDestroy();
    stopSelf();
}

@Override
protected void onHandleWork(@NonNull Intent intent) {

}
private boolean canDrawOnScreen() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return canDrawOnScreenM();
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        return canDrawOverlaysUsingReflection(getApplicationContext());
    } else
        return true;
}

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean canDrawOnScreenM() {
    return Settings.canDrawOverlays(getApplicationContext());
}


@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static boolean canDrawOverlaysUsingReflection(Context context) {
    try {
        AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        Class clazz = AppOpsManager.class;
        Method dispatchMethod = clazz.getMethod("checkOp", new Class[]{int.class, int.class, String.class});
        //AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24
        int mode = (Integer) dispatchMethod.invoke(manager, new Object[]{24, Binder.getCallingUid(), context.getApplicationContext().getPackageName()});
        return AppOpsManager.MODE_ALLOWED == mode;
    } catch (Exception e) {
        return false;
    }
}

}

错误

  java.lang.RuntimeException: Unable to create service com.appmaster.akash.messageplus.Services.MainService: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@463b2ce -- permission denied for window type 2002
                                                                                 at android.app.ActivityThread.handleCreateService(ActivityThread.java:3414)
                                                                                 at android.app.ActivityThread.-wrap4(Unknown Source:0)
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                 at android.os.Looper.loop(Looper.java:164)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                              Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@463b2ce -- permission denied for window type 2002
                                                                                 at android.view.ViewRootImpl.setView(ViewRootImpl.java:789)
                                                                                 at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
                                                                                 at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
                                                                                 at com.appmaster.akash.messageplus.Services.MainService.onCreate(MainService.java:83)
                                                                                 at android.app.ActivityThread.handleCreateService(ActivityThread.java:3404)
                                                                                 at android.app.ActivityThread.-wrap4(Unknown Source:0) 
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683) 
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                                                 at android.os.Looper.loop(Looper.java:164) 
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6541) 
                                                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                                                 at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

此特定服务在较低的API中可以很好地工作,但是在使用26时遇到了麻烦...我不确定如何授予服务权限,但仍然尝试过...所以有人可以帮我解决问题错误...这只是一项基本服务...同样在较低的API中,我也不知道如何直接从应用程序授予权限,因此我进入设置并手动进行操作,然后它可以工作。因此,如果有人为我提供所有API的帮助,那就太好了

1 个答案:

答案 0 :(得分:0)

您不能直接从应用程序授予此权限-是设计使用户必须导航到系统/应用程序设置并在其中启用它。

另外,由于API 26(Oreo)dir_list = ['lines-data', 'abgafhb', 'tmp-data.tar', '100', '115.4', '125'] new_list = [] for x in dir_list: try: float(x) new_list.append(x) except (ValueError, TypeError): pass print dir_list # will not have changed print new_list # will contain only strings that can be converted to float 也已被弃用,如果您定位的是api 26或更高版本,则会使您的应用程序崩溃。您需要将其替换为WindowManager.LayoutParams.TYPE_PHONE