2011年4月21日 星期四

Load Image

Load Image
    String myJpgPath = "/sdcard/test2.jpg";
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2;
    Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
    jpgView.setImageBitmap(bm);

Notification

Notification
簡易範例
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
     
    Notification notification = new Notification();
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    mNotificationManager.notify(123, notification);

2011年4月20日 星期三

Light感測器

Light感測器
    public void onCreate(Bundle savedInstanceState) {
        ................
        // get reference to SensorManager
        SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
        sm.registerListener(lsn, sensor, SensorManager.SENSOR_LIGHT);
    }

    SensorEventListener lsn = new SensorEventListener() {
        public void onAccuracyChanged(Sensor sensor, int accuracy) { }

        public void onSensorChanged(SensorEvent event) {
            // light sensor informations
            cloudy.setText(String.valueOf(SensorManager.LIGHT_CLOUDY));
            fullmoon.setText(String.valueOf(SensorManager.LIGHT_FULLMOON));
            no_moon.setText(String.valueOf(SensorManager.LIGHT_NO_MOON));
            overcast.setText(String.valueOf(SensorManager.LIGHT_OVERCAST));
            shade.setText(String.valueOf(SensorManager.LIGHT_SHADE));
            sunlight.setText(String.valueOf(SensorManager.LIGHT_SUNLIGHT));
            sunlight_max.setText(String.valueOf(SensorManager.LIGHT_SUNLIGHT_MAX));
            sunrise.setText(String.valueOf(SensorManager.LIGHT_SUNRISE));
            // light sensor values
            txtMsg.setText("Ambient light level = " + event.values[0] + " lux");
        }
    };

FingerPaint功能

FingerPaint功能
下面為一繪圖的範例
    public class Project1 extends Activity {
        private Bitmap  mBitmap;
        private MyView mView;

        public void onCreate (Bundle bundle) {
            super.onCreate(bundle);
            // remove the title, and display "full screen"
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            this.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
            // get the windows resolution, for bitmap use
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            // create a new bitmap for paint
            mBitmap = Bitmap.createBitmap(dm.widthPixels, dm.heightPixels, Bitmap.Config.ARGB_8888);
            // use "MyView" class, this is define by author
            mView = new MyView(this);
            setContentView(mView);
        }

        private class MyView extends View {
            private Canvas mCanvas;
            private Path mPath;
            private Paint mBitmapPaint;
            private Paint mPaint;

            private float new_x, new_y;
            private float old_x, old_y;

            public MyView(Context context) {
                super(context);
                // create and initial object
                mCanvas = new Canvas(mBitmap);
                mPath = new Path();
                mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        
                mPaint = new Paint();
                // make paint more smooth
                mPaint.setAntiAlias(true);
                mPaint.setDither(true);
                // (1.FILL 2.FILL_AND_STROKE 3.STROKE)
                mPaint.setStyle(Paint.Style.STROKE);
                // (1.BEVEL 2.MITER 3.ROUND) default is MITER
                mPaint.setStrokeJoin(Paint.Join.ROUND);
                // (1.BUTT 2.ROUND 3.SQUARE) default is BUIT
                mPaint.setStrokeCap(Paint.Cap.ROUND);
                // if set "0", will be a line
                mPaint.setStrokeWidth(12);
                mPaint.setColor(Color.GREEN);
            }
    
            protected void onDraw(Canvas canvas) {
                // set background color
                canvas.drawColor(Color.WHITE);
                // draw the specified bitmap
                canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
                // the path will be filled or framed based on the Style in the paint
                canvas.drawPath(mPath, mPaint);
            }
 
            public boolean onTouchEvent(MotionEvent event) {
                new_x = event.getX();
                new_y = event.getY();
      
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // save the previous path, then reset the path
                    mPath.reset();
                    // start position
                    mPath.moveTo(new_x, new_y);
                    old_x = new_x;
                    old_y = new_y;
                }
                else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    float dx = Math.abs(new_x - old_x);
                    float dy = Math.abs(new_y - old_y);
          
                    if (dx >= 4 || dy >= 4) {
                        // set path from (old_x, old_y) to ((new_x + old_x)/2, (new_y + old_y)/2)
                        mPath.quadTo(old_x, old_y, (new_x + old_x)/2, (new_y + old_y)/2);
                        old_x = new_x;
                        old_y = new_y;
                    }
                }
                else if (event.getAction() == MotionEvent.ACTION_UP) {
                    // unknown, this line like no used
                    mPath.lineTo(old_x, old_y);
                    // paint the path when "ACTION_UP"
                    mCanvas.drawPath(mPath, mPaint);
                    // save the paint
                    mPath.reset();
                }
      
                // update the paint, it will recall the onDraw function
                invalidate();
                return true;
            }
        }
    }

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");
        }
    }