2011年4月18日 星期一

WiFi功能

WiFi功能
這邊簡單介紹WIFI開關的功能
    public class wifi extends Activity implements OnCheckedChangeListener{
        private WifiManager wifiManager;
        private WifiInfo wifiInfo;
        private CheckBox chkOpenCloseWifiBox;
        private List<WifiConfiguration> wifiConfigurations;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.display);
            // 獲得WifiManager對象
            wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
       
            // 獲得連接訊息
            wifiInfo = wifiManager.getConnectionInfo();
            chkOpenCloseWifiBox = (CheckBox) findViewById(R.id.chkOpenCloseWifi);
            TextView tvWifiConfigurations = (TextView) findViewById(R.id.tvWifiConfigurations);
            TextView tvWifiInfo = (TextView) findViewById(R.id.tvWifiInfo);       
            chkOpenCloseWifiBox.setOnCheckedChangeListener(this);
            // 根據目前WiFi狀態設置輸出訊息
            if (wifiManager.isWifiEnabled()) {
                chkOpenCloseWifiBox.setText("Wifi opened");
                chkOpenCloseWifiBox.setChecked(true);
            }
            else {
                chkOpenCloseWifiBox.setText("Wifi closed");
                chkOpenCloseWifiBox.setChecked(false);
            }
       
            // 輸出WIFI訊息
            StringBuffer sb = new StringBuffer();
            sb.append("Wifi Info\n");
            sb.append("MAC Address:" + wifiInfo.getMacAddress() + "\n");
            sb.append("SSID:" + wifiInfo.getSSID() + "\n");
            sb.append("IP Address(int):" + wifiInfo.getIpAddress() + "\n");
            sb.append("IP Address(Hex):" + Integer.toHexString(wifiInfo.getIpAddress()) + "\n");
            sb.append("IP Address:" + ipIntToString(wifiInfo.getIpAddress()) + "\n");
            sb.append("Network ID:" + wifiInfo.getNetworkId() + "\n");
            sb.append("Network Speed:" + Integer.toString(wifiInfo.getLinkSpeed()) + "\n");
            sb.append("Signal Strength:" + Integer.toString(wifiInfo.getRssi()) + "\n");
            tvWifiInfo.setText(sb.toString());
            // 得到配置好的網路
            wifiConfigurations = wifiManager.getConfiguredNetworks();
            tvWifiConfigurations.setText("Had connected wifi\n");
            for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
                tvWifiConfigurations.setText(tvWifiConfigurations.getText() + wifiConfiguration.SSID + "\n");
            }
        }

        // 將int型態的IP轉換成文字型態
        private String ipIntToString(int ip) {
            try {
                byte[] bytes = new byte[4];
                bytes[0] = (byte) (0xff & ip);
                bytes[1] = (byte) ((0xff00 & ip) >> 8);
                bytes[2] = (byte) ((0xff0000 & ip) >> 16);
                bytes[3] = (byte) ((0xff000000 & ip) >> 24);
                return Inet4Address.getByAddress(bytes).getHostAddress();
            }
            catch (Exception e) {
                return "";
            }
        }
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // 當選中複選框時打開WiFi
            if (isChecked) {
                wifiManager.setWifiEnabled(true);
                chkOpenCloseWifiBox.setText("Wifi opened");
            }
            // 當取消複選框時關閉WiFi
            else {
                wifiManager.setWifiEnabled(false);
                chkOpenCloseWifiBox.setText("Wifi closed");
            }
        }
    }

ProgressBar物件

ProgressBar物件
進度條,寫在Handler 裡更新狀態,參考如下
    public class progressbar extends Activity {
        ProgressBar myProgressBar; 
        int myProgress = 0;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
       
            myProgressBar = (ProgressBar)findViewById(R.id.progressbar);
            myProgressBar.setProgress(myProgress);
            // 開啟另一個執行緒,每0.1秒鐘送出一個訊息
            new Thread( new Runnable()
                public void run() {
                    while(myProgress<100){ 
                        try{
                            myHandle.sendMessage(myHandle.obtainMessage());
                            Thread.sleep(100);
                        }
                        catch(Throwable t){
                        }
                    }
                }
            }).start();
        } 
        // 每進來一次,增加一百分比
        Handler myHandle = new Handler(){ 
            public void handleMessage(Message msg) { 
                myProgress++; 
                myProgressBar.setProgress(myProgress); 
            }
        };
}

OnTouchEvent偵測

OnTouchEvent偵測
透過下列程式,可偵測Touch的動作
MotionEvent.ACTION_DOWN:壓下時觸發
MotionEvent.ACTION_MOVE:移動時觸發
MotionEvent.ACTION_UP:離開時觸發
    public boolean onTouchEvent(MotionEvent event){
        switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            temp_x = (int) event.getX();
            temp_y = (int) event.getY();
            break;
        case MotionEvent.ACTION_MOVE :
            break;
        case MotionEvent.ACTION_UP :
            break;
        default :
            break;
        }
        return false; 
    }

event.getPointerCount() get count number

Accelerometer感測器

Accelerometer感測器
加速度感測器,主要運用於感應手機的運動
values[0]:空間座標中X軸方向上的加速度減去重力加速度在X軸的分量。
values[1]:空間座標中Y軸方向上的加速度減去重力加速度在Y軸的分量。
values[2]:空間座標中Z軸方向上的加速度減去重力加速度在Z軸的分量。

    // 設定感測器
    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    sm.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_NORMAL);

    // 接收感測器資訊
    SensorEventListener lsn = new SensorEventListener() {
        public void onAccuracyChanged(Sensor sensor, int accuracy) { }
        public void onSensorChanged(SensorEvent event) {
            gsensor_info.setText(
                "(x,y,z) = (" +  event.values[0] + "," + event.values[1] + "," + event.values[2] + ")");
        }
    };

Application類別

Application類別
新增一AP屬性的Class
然後可以透過getApplicationContext()的方式
即可使用共用的API

    API.java
    public class API extends Application {
        public void initial() {
            // write initial in this
        }
        public Class<?> next_test() {
            return finish.class;
        }
    }

    xxx.java
    API function = ((API)getApplicationContext());
    function.initial();

    Intent trigger = new Intent();
    trigger.setClass(xxx.this, function.next_test());
    startActivity(trigger);
    finish();

DisplayResolution資訊

DisplayResolution資訊
透過DisplayMetrics物件,可以抓取目前顯示面板的相關資訊

    public class displayresolution extends Activity {
        public void onCreate(Bundle savedInstanceState) {
            ..........
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            textScreen.setText(
                "Screen Width: " + String.valueOf(dm.widthPixels) + "\n" +
                "Screen Height: " + String.valueOf(dm.heightPixels) + "\n" +
                "Density: " + String.valueOf(dm.density) + "\n" +
                "DensityDPI: " + String.valueOf(dm.densityDpi) + "\n" +
                "Scaled Density: " + String.valueOf(dm.scaledDensity) + "\n" +
                "X DPI: " + String.valueOf(dm.xdpi) + "\n" +
                "Y DPI: " + String.valueOf(dm.ydpi) + "\n");
        }
    }

2011年4月15日 星期五

Battery資訊

Battery資訊
利用BroadcastReceiverIntentFilter物件偵測Battery資訊
    public void onCreate() {
        .......
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(mBroadcastReceiver, filter);
    }

    public void onDestroy() {
        .............
        unregisterReceiver(mBroadcastReceiver);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                // status
                switch (intent.getIntExtra("status", 0)) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    statusString = "unknown";
                    break; 
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    statusString = "charging";
                    break; 
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    statusString = "discharging";
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    statusString = "not charging";
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    statusString = "full";
                    break;
                default:
                    statusString = "unknown";
                    break;
                }
                // health
                switch (intent.getIntExtra("health", 0)) {
                case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                    healthString = "unknown";
                    break;
                case BatteryManager.BATTERY_HEALTH_GOOD:
                    healthString = "good";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                    healthString = "over heat";
                    break;
                case BatteryManager.BATTERY_HEALTH_DEAD:
                    healthString = "dead";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                    healthString = "over voltage";
                    break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                    healthString = "unspecified failure";
                    break;
                default:
                    healthString = "unknown";
                    break;
                }
                // plugged
                switch (intent.getIntExtra("plugged", 0)) {
                case BatteryManager.BATTERY_PLUGGED_AC:
                    acString = "plugged ac";
                    break;
                case BatteryManager.BATTERY_PLUGGED_USB:
                    acString = "plugged usb";
                    break;
                default :
                    acString = "disconnect";
                    break;
                }
                // others
                boolean present = intent.getBooleanExtra("present", false);
                int level = intent.getIntExtra("level", 0);
                int scale = intent.getIntExtra("scale", 0);
                int icon_small = intent.getIntExtra("icon-small", 0);
                int voltage = intent.getIntExtra("voltage", 0);
                int temperature = intent.getIntExtra("temperature", 0);
                String technology = intent.getStringExtra("technology");
            }
        }
    };