Android Управление файлами сервиса API распределения - PullRequest
1 голос
/ 25 марта 2020

Я тестирую android API управления, используя localhost в качестве URL обратного вызова. Я следовал за каждым шагом, следующим за этим URL Android Пример API управления . Теперь я застрял на месте .. Согласно этому руководству, я загружаю файл json из учетной записи службы. Теперь я копирую этот json файл и сохраняю в папке приложения моего проекта. Это мое предприятие. json файл Снимок экрана: файл json в android studio

, и я просто указываю расположение папки как предприятие. json в строке местоположения Это мое code

private static final String PROJECT_ID = "enterprise-271814";
    private static final String SERVICE_ACCOUNT_CREDENTIAL_FILE =
            "enterprise.json";

    private static final String POLICY_ID = "samplePolicy";

    /** The package name of the COSU app. */
    private static final String COSU_APP_PACKAGE_NAME =
            "com.ariaware.devicepoliceycontroller";

    /** The OAuth scope for the Android Management API. */
    private static final String OAUTH_SCOPE =
            "https://www.googleapis.com/auth/androidmanagement";


    private static final String APP_NAME = "Device Policey Controller";

    private final AndroidManagement androidManagementClient;


    public Sample(AndroidManagement androidManagementClient) {
        this.androidManagementClient = androidManagementClient;
    }

    public void run() throws IOException {
        // Create an enterprise. If you've already created an enterprise, the
        // createEnterprise call can be commented out and replaced with your
        // enterprise name.
        String enterpriseName = createEnterprise();
        System.out.println("Enterprise created with name: " + enterpriseName);

        // Set the policy to be used by the device.
        setPolicy(enterpriseName, POLICY_ID, getCosuPolicy());

        // Create an enrollment token to enroll the device.
        String token = createEnrollmentToken(enterpriseName, POLICY_ID);
        System.out.println("Enrollment token (to be typed on device): " + token);

        // List some of the devices for the enterprise. There will be no devices for
        // a newly created enterprise, but you can run the app again with an
        // existing enterprise after enrolling a device.
        List<Device> devices = listDevices(enterpriseName);
        for (Device device : devices) {
            System.out.println("Found device with name: " + device.getName());
        }

        // If there are any devices, reboot one.
        if (devices.isEmpty()) {
            System.out.println("No devices found.");
        } else {
            rebootDevice(devices.get(0));
        }
    }

    public static AndroidManagement getAndroidManagementClient()
            throws IOException, GeneralSecurityException {
        try (FileInputStream input =
                     new FileInputStream(SERVICE_ACCOUNT_CREDENTIAL_FILE)) {
            GoogleCredential credential =
                    GoogleCredential.fromStream(input)
                            .createScoped(Collections.singleton(OAUTH_SCOPE));
            return new AndroidManagement.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(),
                    JacksonFactory.getDefaultInstance(),
                    credential)
                    .setApplicationName(APP_NAME)
                    .build();
        }
    }

    private String createEnterprise() throws IOException {
        // Initiate signup process.
        System.out.println("Creating signup URL...");
        SignupUrl signupUrl =
                androidManagementClient
                        .signupUrls()
                        .create()
                        .setProjectId(PROJECT_ID)
                        .setCallbackUrl("https://localhost:9999")
                        .execute();
        System.out.print(
                "To sign up for a new enterprise, open this URL in your browser: ");
        System.out.println(signupUrl.getUrl());
        System.out.println(
                "After signup, you will see an error page in the browser.");
        System.out.print(
                "Paste the enterpriseToken value from the error page URL here: ");
        String enterpriseToken =
                new BufferedReader(new InputStreamReader(System.in)).readLine();

        // Create the enterprise.
        System.out.println("Creating enterprise...");
        return androidManagementClient
                .enterprises()
                .create(new Enterprise())
                .setProjectId(PROJECT_ID)
                .setSignupUrlName(signupUrl.getName())
                .setEnterpriseToken(enterpriseToken)
                .execute()
                .getName();
    }

    private Policy getCosuPolicy() {
        List<String> categories = new ArrayList<>();
        categories.add("android.intent.category.HOME");
        categories.add("android.intent.category.DEFAULT");

        return new Policy()
                .setApplications(
                        Collections.singletonList(
                                new ApplicationPolicy()
                                        .setPackageName(COSU_APP_PACKAGE_NAME)
                                        .setInstallType("FORCE_INSTALLED")
                                        .setDefaultPermissionPolicy("GRANT")
                                        .setLockTaskAllowed(true)))
                .setPersistentPreferredActivities(
                        Collections.singletonList(
                                new PersistentPreferredActivity()
                                        .setReceiverActivity(COSU_APP_PACKAGE_NAME)
                                        .setActions(
                                                Collections.singletonList("android.intent.action.MAIN"))
                                        .setCategories(categories)))
                .setKeyguardDisabled(true)
                .setStatusBarDisabled(true);
    }

    private void setPolicy(String enterpriseName, String policyId, Policy policy)
            throws IOException {
        System.out.println("Setting policy...");
        String name = enterpriseName + "/policies/" + policyId;
        androidManagementClient
                .enterprises()
                .policies()
                .patch(name, policy)
                .execute();
    }

    private String createEnrollmentToken(String enterpriseName, String policyId)
            throws IOException {
        System.out.println("Creating enrollment token...");
        EnrollmentToken token =
                new EnrollmentToken().setPolicyName(policyId).setDuration("86400s");
        return androidManagementClient
                .enterprises()
                .enrollmentTokens()
                .create(enterpriseName, token)
                .execute()
                .getValue();
    }

    private List<Device> listDevices(String enterpriseName) throws IOException {
        System.out.println("Listing devices...");
        ListDevicesResponse response =
                androidManagementClient
                        .enterprises()
                        .devices()
                        .list(enterpriseName)
                        .execute();
        return response.getDevices() ==null
                ? new ArrayList<Device>() : response.getDevices();

    }

    private void rebootDevice(Device device) throws IOException {
        System.out.println(
                "Sending reboot command to " + device.getName() + "...");
        Command command = new Command().setType("REBOOT");
        androidManagementClient
                .enterprises()
                .devices()
                .issueCommand(device.getName(), command)
                .execute();
    }

Кроме того, я впервые использую android API управления, и я не знаю, как правильно его реализовать. Любой, кто имеет опыт в этом kinllt, направит меня немного. Я нашел много об этом, но я не нашел ни одного полезного учебника

1 Ответ

1 голос
/ 15 апреля 2020

Для Android необходимо сохранить файл учетной записи службы либо в папке assets, либо в папке raw.

Этот поток предоставляет код для нескольких способов загрузки данных json в InputStream в зависимости от выбранного местоположения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...