Android开发---设置桌面图标不显示

做Camera功能开发时,有一条需求是:移除Camera组件,观察桌面Camera图标,Camera组件要相应消失。
针对这条需求,实现代码如下:

package com.android.camera;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.util.Log;

//  如果当前设备没有Camera组件,或者Camera组件连接不良,则不在桌面显示Camera图标。
//  需要监听开机广播,并且生效一次后,立马失效,不在运行。

public class DisableCameraReceiver extends BroadcastReceiver {
    private static final String TAG = "DisableCameraReceiver";
    private static final String ACTIVITIES[] = { "com.android.camera.CameraLauncher",
            "com.android.camera.VideoCamera", "com.android.camera.CameraActivity" };

    @Override
    public void onReceive(Context context, Intent intent) {
        // Disable camera-related activities if there is no camera.
        boolean needCameraActivity = FeatureSwitcher.isOnlyCheckBackCamera() ? hasBackCamera()
                : hasCamera();

        if (!needCameraActivity) {
            Log.d(TAG, "disable all camera activities");
            for (int i = 0; i < ACTIVITIES.length; i++) {   
                // 最重要的代码,如果判断没有Camera组件,则调用disableComponent()方法。
                disableComponent(context, ACTIVITIES[i]);
            }
        }

        // 一旦运行一次,就失效
        disableComponent(context, "com.android.camera.DisableCameraReceiver");
    }

    private boolean hasCamera() {
        int n = Camera.getNumberOfCameras();
        Log.d(TAG, "number of camera: " + n);
        return (n > 0);
    }

    private boolean hasBackCamera() {
        int n = Camera.getNumberOfCameras();
        CameraInfo info = new CameraInfo();
        for (int i = 0; i < n; i++) {
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
                Log.d(TAG, "back camera found: " + i);
                return true;
            }
        }
        Log.d(TAG, "no back camera");
        return false;
    }

    private void disableComponent(Context context, String klass) {
        ComponentName name = new ComponentName(context, klass);
        PackageManager pm = context.getPackageManager();

        // We need the DONT_KILL_APP flag, otherwise we will be killed
        // immediately because we are in the same app.
        pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
}}

同时在Androidmenifest.xml中注册广播

<receiver android:name="com.android.camera.DisableCameraReceiver">
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
intent-filter>
receiver>

你可能感兴趣的:(android-camera)