Sep 28, 2012

TextView 왼쪽 아이콘

android:drawableLeft="@drawable/ic_launcher"

or

TextView tv; 
Drawable icon; 


Bitmap b = Bitmap.createScaledBitmap(((BitmapDrawable) icon).getBitmap(), 120, 120, false);
icon = new BitmapDrawable(b); 
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());

tv.setTextSize(12); 
tv.setGravity(Gravity.CENTER); 
tv.setCompoundDrawables(icon, null, null, null);

Sep 10, 2012

GPS 관련



LocationManager
위치 기반 서비스를 관리하는 Class
Location
위치 정보를 가지고있는 Class
LocationPovider
위치를 결정하는데 사용되는 공급자를 지정.
위치 공급자 식별자
LocationManager.GPS_PROVIDER
LocationManager.NETWORK_PROVIDER
LocationListener
위치 갱신에 따른 위치 정보를 수신할 수 있는 Listener Interface
Permission
ACCESS_FINE_LOCATION - 정밀한위치를가져온다.
ACCESS_COARSE_LOCATION - 낮은정밀도의위치를가져온다.



Aug 29, 2012

서비스 바인드와 핸들러 구현 (옵저버 패턴)

//// mActivity.java  
Messenger mService = null;  
boolean bindService = false;

class IncomingHandler extends Handler {
    @Override  
    public void handleMessage(Message msg) {

    }  
}  

final Messenger mMessenger = new Messenger(new IncomingHandler());

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {

        mService = new Messenger(service);  

        try {  
            Message msg = Message.obtain(null, MessengerService.MSG_REGISTER_CLIENT);
            msg.replyTo = mMessenger;  
            mService.send(msg);  

        } catch (RemoteException e) {  
          
        }  
    }  

    public void onServiceDisconnected(ComponentName className) {

        mService = null;  
    }  
};  

void doBindService() {  
    // Establish a connection with the service. We use an explicit
    // class name because there is no reason to be able to let other
    // applications replace our component.  
    bindService = getApplicationContext().bindService(new Intent(mActivity.this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);  

}  

void doUnbindService() {  
    if (bindService) {  
        // If we have received the service, and hence registered with it, then now is the time to unregister. 
        if (mService != null) {
            try {  
                Message msg = Message.obtain(null, MessengerService.MSG_UNREGISTER_CLIENT);
                msg.replyTo = mMessenger;  
                mService.send(msg);  
            } catch (RemoteException e) {  
                // There is nothing special we need to do if the service has crashed. 
            }  
        }  

        // Detach our existing connection.  
        getApplicationContext().unbindService(mConnection);  
        bindService = false;  
    }  
}  


////MessengerService.java  

     
    /** 
     * Command to the service to register a client, receiving callbacks 
     * from the service.  The Message's replyTo field must be a Messenger of 
     * the client where callbacks should be sent. 
     */ 
    public final static int MSG_REGISTER_CLIENT = 1;
    /** 
     * Command to the service to unregister a client, ot stop receiving callbacks 
     * from the service.  The Message's replyTo field must be a Messenger of 
     * the client as previously given with MSG_REGISTER_CLIENT. 
     */ 
    public final static int MSG_UNREGISTER_CLIENT = 2;
    /** 
     * Command to service to set a new value.  This can be sent to the 
     * service to supply a new value, and will be sent by the service to 
     * any registered clients with the new value. 
     */ 
    static final int MSG_SET_VALUE = 3;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); 

    private final Messenger mMessenger = new Messenger(new IncomingHandler());

    private class IncomingHandler extends Handler {
        @Override 
        public void handleMessage(Message msg) {
            switch (msg.what) { 
            case MSG_REGISTER_CLIENT: 
                mClients.add(msg.replyTo); 
                break; 
            case MSG_UNREGISTER_CLIENT: 
                mClients.remove(msg.replyTo); 
                break; 
            } 
        } 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
        return mMessenger.getBinder(); 
    } 

    /** 
     * Send Message to Clients. 
     * @param msg Message 
     */ 
    private void sendMessageToClients(Message msg) {
        for (int i = mClients.size() - 1; i >= 0; i--) { 
            try { 
                // send a message to mClients. 
                // you may have handle this massage from IncomingHandler at any Activity
                mClients.get(i).send(msg); 
            } catch (RemoteException e) { 
                // The client is dead. Remove it from the list; 
                // we are going through the list from back to front
                // so this is safe to do inside the loop. 
                mClients.remove(i); 
            } 
        } 
    }

Aug 16, 2012

Home Launcher 등록



<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
 </intent-filter>

Aug 14, 2012

어두워짐 방지 (screen full wake up)

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "screen"); 
wl.acquire(); 
//     ..screen will stay on during this section.. 
//wl.release();



<uses-permission android:name="android.permission.WAKE_LOCK"/>

Aug 7, 2012

Create Thread


1.
    class mThread extends Thread {
        @Override 
        public void run() {
             
             
        } 
    } 
     
     
    mThread t = new mThread(); 
    t.start();

2.

Thread thread = new Thread(){
 @Override
 public void run() {
  // TODO Auto-generated method stub
 }
};

Timer

    // 타미어 테스크 정의     
    TimerTask mTask = new TimerTask() { 
        @Override 
        public void run() {
            // do something!! 
        } 
    }; 
     
     
    // 사용 
    Timer mTimer = new Timer(); 
    mTimer.schedule(mTask, WHEN, PERIOD);

Jun 28, 2012

Start Activity When Boot Completed

public class mReceiver extends BroadcastReceiver {

    @Override 
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Log.d("tag", "boot ok"); 
            Intent i = new Intent(context, sampleActivity.class); 
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
            context.startActivity(i); 
        } 
    } 
}
Need Uses Permission : android.permission.RECEIVE_BOOT_COMPLETED

Jun 7, 2012

edittext 특수문자 제한, 한글만 입력

// 영문 + 숫자 
public InputFilter filterAlphaNum = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        Pattern ps = Pattern.compile("^[a-zA-Z0-9]*$"); 
        if (!ps.matcher(source).matches()) { 
            return ""; 
        } 
        return null; 
    } 
}; 

// 한글 
public InputFilter filterKor = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        Pattern ps = Pattern.compile("^[ㄱ-ㅣ가-힣]*$"); 
        if (!ps.matcher(source).matches()) { 
            return ""; 
        } 
        return null; 
    } 
}; 


editText.setFilters(new InputFilter[]{filterAlphaNum}); 

패키지 정보 가져오기

ArrayList<PackageInfo> packages = new ArrayList<PackageInfo>(); 
PackageManager pm; 

void getPackeges() { 
    pm = (PackageManager) this.getPackageManager(); 
    List<PackageInfo> allPackages = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);

    for (int i = 0; i < allPackages.size(); i++)
        if (!isSystemApplication(allPackages.get(i))) 
            packages.add(allPackages.get(i)); 
} 

boolean isSystemApplication(PackageInfo packinfo) { 
    return (packinfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? true : false;
}

Install, Uninstall 소스

Uri uri = Uri.fromParts("package", packageName, null);    
Intent i = new Intent(Intent.ACTION_DELETE, uri);    
startActivity(i);


Uri uri= Uri.fromParts("package", packageName , null); 
Intent i = new Intent(Intent.ACTION_PACKAGE_ADDED, uri); 
startActivity(i);

터치 좌표, 터치 다운 이벤트

button.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) {
        float x = event.getX(); 
        float y = event.getY(); 
        switch (event.getAction()) { 
        case MotionEvent.ACTION_DOWN: 

            break; 
        case MotionEvent.ACTION_UP: 
        } 
        return pressed; 
    } 
});

Jun 5, 2012

screen capture

public void screenshot(View view) throws Exception {

    view.setDrawingCacheEnabled(true); 
    Bitmap screenshot = Bitmap.createBitmap(view.getDrawingCache()); 
    view.setDrawingCacheEnabled(false); 

    if (screenshot == null) { 
        Log.e("screencast", "error : could not get drawing cache..."); 
        return; 
    } 

    File dir = Environment.getExternalStorageDirectory(); 
    String baseName = "screencast"; 
    String extention = ".jpg"; 
    String filename = baseName + extention; 

    try { 
        File f = new File(dir, filename); 
        f.createNewFile(); 

        OutputStream outStream = new FileOutputStream(f); 

        screenshot.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
        outStream.flush(); 
        outStream.close(); 

        Log.d("screencast", "captured to " + f.getPath() + "(" + f.length() + "byte)"); 

    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
}

StartActivity, StartService

Intent i = new Intent(currentActivity.this, targetActivity.class); 
startActivity(i); 


Intent i = new Intent(currentActivity.this, targetService.class);
startService(i);

Button setOnclickListener

button.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) {
       
    } 
});

Jun 4, 2012

getLocalIPAddressList

private ArrayList<String> getLocalIPAddressList() {
    ArrayList<String> mAddress = new ArrayList<String>(); 
    try { 
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement(); 
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement(); 
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                     
                        mAddress.add(inetAddress.getHostAddress().toString()); 
                } 
            } 
        } 
    } catch (SocketException e) { 
        Log.e(TAG, "Fail to get IP Address : " + e); 
    } 

    return mAddress; 
}

Mar 25, 2012

해상도 구하는 방법


전체 해상도
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

View의 해상도 (context 필요)
int mWidth = context.getResources().getDisplayMetrics().widthPixels;
int mHeight = context.getResources().getDisplayMetrics().heightPixels;

Mar 5, 2012

Activity의 Title bar 제거


1. 코드
requestWindowFeature(Window.FEATURE_NO_TITLE);

2. Manifest 수정
android:theme="@android:style/Theme.NoTitleBar"