public class Main {
public static void main(String[] args) {
System.out.print(byteToHexString("abcde".getBytes()));
}
public static String byteToHexString(byte[] b) {
char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
StringBuffer sb = new StringBuffer();
for (byte i : b) {
sb.append(digit[((i & 0xF0) >> 4)]);
sb.append(digit[i & 0x0F] + " ");
}
return sb.toString();
}
}
output:
61 62 63 64 65
Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts
Jun 15, 2015
Dec 11, 2014
날짜 표현 DateFormat, Custom Date Text View
Date today; String output; SimpleDateFormat formatter; formatter = new SimpleDateFormat(pattern, currentLocale); today = new Date(); output = formatter.format(today); System.out.println(pattern + " " + output);
| Pattern | Output |
|---|---|
| dd.MM.yy | 30.06.09 |
| yyyy.MM.dd G 'at' hh:mm:ss z | 2009.06.30 AD at 08:29:36 PDT |
| EEE, MMM d, ''yy | Tue, Jun 30, '09 |
| h:mm a | 8:29 PM |
| H:mm | 8:29 |
| H:mm:ss:SSS | 8:28:36:249 |
| K:mm a,z | 8:29 AM,PDT |
| yyyy.MMMMM.dd GGG hh:mm aaa | 2009.June.30 AD 08:29 AM |
Custom Date Text View
public class MDateView extends View { private final static String FORMAT_DEFULAT = "yyyy.MM.dd"; private boolean isTickable = false; private boolean isColon = true; private Calendar mCalendar; private Runnable mTickerRunnable; private Handler mHandler; private String mFormat = FORMAT_DEFULAT; private String mDateString = "", mTimeString = ""; private Paint mDatePaint, mTimePaint; public MDateView(Context context) { super(context); initClock(context); } public MDateView(Context context, AttributeSet attrs) { super(context, attrs); initClock(context); } private void initClock(Context context) { if (mCalendar == null) { mCalendar = Calendar.getInstance(); } mDatePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDatePaint.setColor(Color.argb(255, 255, 255, 255)); mDatePaint.setTextSize(18); mDatePaint.setTextAlign(Align.LEFT); mTimePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTimePaint.setColor(Color.argb(255, 255, 255, 255)); mTimePaint.setTextSize(24); mTimePaint.setTextAlign(Align.LEFT); } @Override protected void onDraw(Canvas canvas) { canvas.drawText(mDateString, 5, 35, mDatePaint); int offsetX = 92; float time_X_Pos = (120 - mTimePaint.measureText(mTimeString, 0, mTimeString.length())) / 2.0f;// center align canvas.drawText(mTimeString, offsetX + time_X_Pos, 35, mTimePaint); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); isTickable = true; mHandler = new Handler(); mTickerRunnable = new Runnable() { public void run() { if (!isTickable) return; mCalendar.setTimeInMillis(System.currentTimeMillis()); mDateString = DateFormat.format(mFormat, mCalendar).toString(); mTimeString = DateFormat.format("k" + (isColon ? ":" : " ") + "mm", mCalendar).toString(); invalidate(); long now = SystemClock.uptimeMillis(); long next = now + (1000 - now % 1000); isColon = !isColon; mHandler.postAtTime(mTickerRunnable, next); } }; mTickerRunnable.run(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isTickable = false; } public void setFormat(String format) { if (mFormat == format) return; mFormat = format; }
Nov 25, 2013
기기의 DPI 확인
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
Log.d("TEST", "DPI = " + displayMetrics.densityDpi);
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
Log.d("TEST", "DPI = " + displayMetrics.densityDpi);
Oct 30, 2013
android(java) 파일 저장 후 리부팅 시 저장안되어 있는 현상
android에서 FileOutputStream 의 write();, flush(); 했는데도 리부팅 시 간헐적으로 파일이 생성되지 않았거나 파일 내 데이터가 변하지 않을 때가 있다.
FileOutputStream 의 flush(); 가 버퍼를 비우는 기능만 수행하고 실제 physical device에 데이터를 저장하지 않아 파일에 데이터를 쓰기까지의 딜레이가 생기는 것이다.
이 때 fos.getFD().sync();의 메서드로 파일시스템 내부의 캐쉬를 모두 physical device로 저장한다.
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(obj.toString().getBytes());
fos.flush();
fos.getFD().sync();
fos.close();
FileOutputStream 의 flush(); 가 버퍼를 비우는 기능만 수행하고 실제 physical device에 데이터를 저장하지 않아 파일에 데이터를 쓰기까지의 딜레이가 생기는 것이다.
이 때 fos.getFD().sync();의 메서드로 파일시스템 내부의 캐쉬를 모두 physical device로 저장한다.
FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(obj.toString().getBytes());
fos.flush();
fos.getFD().sync();
fos.close();
Oct 7, 2013
Shuffle 기능
List< Integer > numbers;
Collections.shuffle( numbers );
// 0부터 6번째 인덱스 데이터 가지고 옴
List< Integer > winningCombination = numbers.subList( 0 , 6 );
// 정렬
Collections.sort( winningCombination );
Sep 28, 2012
TextView 왼쪽 아이콘
android:drawableLeft="@drawable/ic_launcher"
or
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) {
} });
Subscribe to:
Posts (Atom)