Programming2011. 10. 15. 03:04
you do not have to use thread,

However, if you want to use "Double-buffering" mechanism. at least you should know how to use Thread.
This code is really messed up though Sorry =)


package com.Circle;

import android.app.Activity;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.content.*;

public class CircleActivity extends Activity {
    /** Called when the activity is first created. */

    MyView vw;                    // Circle을 만들기 위한 객체 선언
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vw = new MyView(this);    // 객체 할당
        setContentView(vw);        // 이 객체를 보여주도록 한다.
       
    }
    public class MyView extends View{    // view클레스를 상속하는 MyView class
        int num = 0;                // 이 변수는 0부터 360까지 증가되는 변수이다
        Paint pnt = new Paint();    // paint 변수 선언
        RectF rf = new RectF(50,50,150,150);    // 타원을 넣기 위한 RectF 클레스 선언
        Thread th = new Thread(new ThreadForCircle());    // 실시간 작동을 위하여 thread를 생성하였다.
                                                // ThreadForCircle은 Runnable interface를 가진다.
        int color;                    // color를 저장하기 위한 변수 선언
       
       
        public MyView(Context context){
            super(context);        //생성자 부분
            color = Color.argb(0xFF, (int)(Math.random()*256), (int)(Math.random()*256), (int)(Math.random()*256));
            // 랜덤한 색깔 생성
            pnt.setAntiAlias(true);    // AntiAlias모드를 on, 더욱 자연스럽다.
            th.start();                // thread를 시작한다.
        }
       
        public void onDraw(Canvas canvas){    // 실질적으로 원을 그리는 함수
            if(num > 360){            // 만약 원하나가 이미 그려졌다면
                color = Color.argb(0xFF, (int)(Math.random()*256), (int)(Math.random()*256), (int)(Math.random()*256));
                // 색깔을 바꾸고
                num=0;
                // 처음부터 다시 그릴 준비를 한하.
            }
            else{
                pnt.setColor(color);    // paint 객체에 색깔을 지정한후
                canvas.drawArc(rf, 0, num, true, pnt);    // 부채꼴을 그린다. num값은 thread에 의해 바뀌며,
                                                        // thread는 onDraw를 호출하게 된다.
                Toast.makeText(CircleActivity.this, new String("hello"), Toast.LENGTH_SHORT).show();
            }
        }
        public int getNum(){            // 부채꼴의 현재 크기를 얻기 위한 함수
            return num;           
        }
       
        public void setNum(int _num){    // 부채꼴의 크기를 변경할 함수
            num = _num;
        }
    }


    public class ThreadForCircle implements Runnable{    // Runnable interface를 가지며
        int returnValue;                                // 변경될 크기가 저장될 변수
        public void run(){                                // thread생성 후에 무조건 run이 실행된다.
            while(true){                                // 반복문을 계속 돌린다.
                try {                                    // sleep을 위한 예외처리
                    Thread.sleep(50);                    // 50/1,000초 쉰다.
                    returnValue = vw.getNum() + 6;        // 6도씩 부채꼴이 증가하게 된ㄷ.
                    vw.setNum(returnValue);                // 이 값을 view의 객체에 넣어준다.
                    vw.postInvalidate();                // invalidate가 아닌데 그 이유는
                                                        // 현재 thread는 onDraw 함수가 없다.
                                                        // thread를 호출한 곳에서 invalidate하게 한다.
                } catch (InterruptedException e) {        // 예외 선언
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }         
            }
        }
    }
   
}

'Programming' 카테고리의 다른 글

Spring3.0 ajax를 이용한 json 주고밖기(@RequestBody)  (0) 2012.11.18
Open SSH Server  (0) 2012.10.08
File copy by using windows API  (0) 2011.08.31
Win32 API tutorial  (0) 2011.08.26
Posted by 박세범

See struct stat and fstat;

pretty simple example, and getMode show a good example in terms of bit operation.



#include <stdio.h>              // 표준입출력헤더파일

   #include <stdlib.h>            

   #include <sys/stat.h>           // stat 구조체가선언되어있는헤더파일

   #include <sys/types.h>          // perror 함수호출을위한헤더파일

   #include <unistd.h>

   #include <fcntl.h>              // file control flag가저장되어있는헤더파일

 

   #define MAX_BUF 64              // BUF 크기를정의한다.

 

  char* getMode(mode_t mode,char* bit);   // getMode 함수는현재파일의속성을출력한다.

 

  int main(int argc, char *argv[])        // 메인함수시작

  {

      int fdForRead;                     // file descriptor for read

      int fdForWrite;                    // file descriptor for write

      char buf[MAX_BUF];                 // to define buffer

      int read_size;                     // readoff셋으로활용되는변수

      int write_size;                           // wrtieoff셋으로활용될변수

      struct stat info;                  // 파일의정보를받을구조체

      int fs;                                   // fstat의리턴값을저장할변수

      int modeInfo;                      // getModemode를받을정수

      char bit[10];                             // rwxrwxrwx로출력하기위한변수

      int i=0;                           // for문의counter 변수

 

      if(argc != 3)                      // 만약arument의사용법이잘못됐다면

      {

          printf("Usage : mycp.out source_file_name destination_file_name\n\n");

                                         // 사용법을알려준후

          exit(-1);                      // 프로그램을종료한다.

      }

 

      fdForRead = open(argv[1], O_RDWR);   // 2번째argument를이용해서파일을열며읽기쓰기가능>

      if(fdForRead <0){                                // 만약읽기가실패한다면

          perror("cannot open the file because : ");  // 메세지를출력후

          exit(-1);                                    // 프로그램을종료한다.

     }

 

     printf("\n\nThis program is coping a file with the mode of file \n");

                                                         // 프로그램실행전출력메세지

 

     fstat(fdForRead, &info);    //fstat      수는file descriptor를이용하여stat 구조체에

                                 // file에대한정보를저장하며여기서우리는mode를얻을수있다.

 

     getMode(info.st_mode,bit);          // getMode는가져온mode정보를rwxrwxrwx 형태로bit에대입한다.

     printf("The mode = %s \n\n",bit);     // 현재파일의모드를출력하고

 

 

/*************************************************************************************

//                         Redirection

 

     // close(STDOUT_FILENO);    // 만약redirection을쓰고싶으면이주석을해제하면된다.

 

 ************************************************************************************/

 

 

     fdForWrite = open(argv[2], O_RDWR | O_CREAT | O_EXCL, info.st_mode);

                                           // stat 구조체에저장된st_mode를이용하여파일을생성하며

                                           // 만약파일명이중복된다면O_EXCL flag로인하여파일이생성되지않>

     if(fdForWrite == -1){                 // 파일생성에실패하거나파일이존재한다면

         perror("cannot open the file because :  ");     // 메세지와errno의메세지를같이출력한후

         exit(-1);                           // 프로그램을종료한다.

     }

      while(1){                                     // while문은파일이다써질때까지반복되며

          read_size = read(fdForRead, buf, MAX_BUF);  // 64바이트씩파일을읽는다

          if(read_size == 0)                       // 만약파일의끝이라면

              break;                               // 반복문을빠져나간다.

          write_size = write(fdForWrite, buf, read_size);     // 64바이트씩새로운file에쓴다.

 

         /******************** Redirection ******************************

                    

          //write_size = write(STDOUT_FILENO, buf, read_size);    // redirection을이용한file 출력

 

         ***************************************************************/    

 }

      printf("Successful!\n");     // 파일복사가완료되면메세지를생성후

      close(fdForRead);             // file descriptor들을닫아준다.

      close(fdForWrite);

      return 0;

  }

 

   char* getMode(mode_t mode,char* bit)       // file mode를출력하는함수

  {

      int i=0;                            // 반복문의counter

      int index=0;                        // index는문자를저장할떄쓰인다

      int modeInfo = 00777 & (unsigned long)mode;     // 777modeAND 연산한후

      for(i=256;i>0;i=i/2){                     // 그내용들을출력하는반복문을실행한다.

          if((modeInfo & i) == i)        // 만약i2^8부터2^0까지바뀌게되며

          {                              // and 연산이i값과같다면그flagset이다.

              if(index%3 == 0)                  // rwx 위치에맞게문자열에저장된다.

                  bit[index] = 'r';

              else if(index%3 == 1)

                  bit[index] = 'w';

              else

                  bit[index] = 'x';

          }

          else

              bit[index] = '-';          // 만약flag0이라면'-'로문자열을채운다.

          index++;                       // index를증가시킨후

      }

      return bit;                     // 받았던문자열을반환한다.

}


'Programming > System programming' 카테고리의 다른 글

dup2() and pipe() system call for pipe fuction in shell  (1) 2011.11.03
sys/types.h  (2) 2011.10.10
Posted by 박세범
please take a look at accept() method,
second and third parameters must have values
don't forget

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    struct sockaddr_in local;
    struct sockaddr_in client;
    int *csize;
    int s;    int s1;    int rc; char buf[1];
    local.sin_family = AF_INET;
    local.sin_port = htons(5300);
    local.sin_addr.s_addr = htonl(INADDR_ANY);
   
    char getTime[255];

    //added by Justin
   
    printf("A server has been started, the port number is reserved as 5300\n\n");


    s = socket(PF_INET, SOCK_STREAM, 0);
    if(s<0){
        perror("socket call failed");
        exit(1);
    }

    rc = bind(s, (struct sockaddr *)&local, sizeof(local));
    if(rc<0){
        perror("bind call failure");
        exit(1);
    }


    printf("A server is waintg for a client request\n\n");

    rc = listen(s,5);
    if(rc){
        perror("listen call failed");
        exit(1);
    }



    csize = sizeof(client);        // this is used to get a ip address using accept()

    s1= accept(s,(struct sockaddr*)&client ,&csize);    // we need to know the ip address of a client
    // to get client address. then we have to send this client
    // address to the client.

    printf("Conntection established!\n\n");

    if(s1<0){
        perror("accept call failed");
        exit(1);
    }

    rc = recv(s1,getTime ,sizeof(getTime), 0);    // rc return the size of the data

    if(rc<=0){
        perror("recv call failed");
        exit(1);
    }

    printf("\nCurrent time from client : %s \n", getTime);        //print current Time

    printf("\n\nA server will send a client's IP address \n");

    rc = send(s1, &client , sizeof(client), 0);        // send a structure of sockaddr_in to the client
    if(rc <= 0)                        // if it failes
    {
        perror("send call failed");
        exit(0);
    }
}





'Programming > Network Programming' 카테고리의 다른 글

TCP programming basis  (0) 2011.10.28
.. no regret..  (0) 2011.10.26
get client IPadrress in server side  (0) 2011.10.10
Reference for unix socket api  (0) 2011.09.29
TCP/IP  (0) 2011.09.21
Posted by 박세범