2014. 5. 15. 11:01 안드로이드


GpsActivity.apk



위치 찾는 소스 예제 

http://www.codeofaninja.com/2014/04/get-the-users-current-location-in-android.html



GoogleMap v2를 이용한 안드로이드 위치 정보 기록 앱입니다.


네비만 찍고 목적지를 향해서 갈때 내가 간 곳의 위치가 어디 쯤이고 어디를 경유해서 갔는지 궁금해서 

만들어 본 앱입니다 ..


요즘 위치 정보 때문에 민감합니다 . 

이 앱은 위치정보를 서버로 보내지 않으니 안심 하셔도 됩니다.

네트워크 퍼미션 사용은 구글 분석기를 이용하기 위해서 선언되었습니다.

구글 분석기는 사용자 패턴을 확인하기 위해 사용했습니다. (화면, 터치이벤트)


평소에는 회사 집만 왔다갔다하니 별로 필요없지만 

주말에 교외로 나갈 때 사용하면 내가 이동한 위치가 기록되어져 있어서 어떤길로 갔는지 확인이 가능합니다.


기록된 정보는 앱의 디비에 기록되고 

앱에 기록된 디비를 파일로 저장하여 메모리  Gpson폴더에 저장됩니다.


기본 화면 [지도]

현재 내 위치를 나타냅니다.



경로화면

앱 디비에 저장된 경로들을 모두 볼수 있습니다.


설정

여러가지 설정이 가능합니다.




영역설정을 클릭하면 날짜를 설정해서 해당 날짜의 저장된 데이터를 지도나 리스트로 확인 가능합니다.

DELAYTIME을 설정해서 백그라운드에서도 해당 딜레이 만큼 위치를 기록합니다.

알림설정은 딜레이 타임만큼의 시간마다 위치가 확인되면 상단 상태바에 노티를 띄움니다 

파일 저장은 앱에 기록된 디비를 파일로 저장하여 메모리  Gpson에 저장됩니다.

파일 보기는 파일 저장을 통해 저장된 파일을 삭제, 메일보내기, 앱에서 읽기의 기능이 있습니다.

GPS환경설정은 단말기의 GPS환경설정을 설정합니다.

초기화 기록된 디비정보만을 모두 지웁니다.







posted by 욱이다
2014. 4. 30. 09:14 안드로이드


CardList2.zip


[출처]/AndroidStaggeredGrid


https://github.com/etsy/AndroidStaggeredGrid

라이브러리 다운 받아서 돌아가게 만들었다

posted by 욱이다
2014. 4. 16. 12:07 안드로이드

cygwin 설치



빨간색 칠해진 DEVEL과 CURL을 체크해서 설치 

(혹시 설치했는데 또 설치하고싶으면 setup.exe파일 다시 실행해서 설치 하고 싶은 것만 체크해서 다시 설치 하면된다)


그러고 나서는 안드로이드에 나와있는 순서대로 하면 된다 

검색해서 나온 블로그에 나와있는 방법대로 하면 안되던데 홈페이지 들어가서 하면 바로 된다.

http://source.android.com/source/downloading.html


cygwin에서의 폴더 이동은 

cd /cygdrive/d/project/a/b  요렇게 넣어주면 폴더 이동이 된다



posted by 욱이다
2014. 4. 8. 14:40 안드로이드

안드로이드 50메가가 넘어가는 파일 다운로드 


생각 없이 쭉 따라 하면 됩니다.

확장 파일은 안드로이드 콘솔에다 업로드 하는데 .. 누구는 압축을 안한 압축파일을 하라고해서 그렇게 하니 됐습니다. 

알집에 보니 압축률 없이 압축하는 방법이 있습니다.

안드로이드에서 샘플이 제공되고 있습니다. 

D:\adt-bundle-windows-x86_64\sdk\extras\google\play_apk_expansion\downloader_sample

파일이 저장되면 아래의 경로에 저장 됩니다.

 Environment.getExternalStorageDirectory() + "/Android/obb/" + thePackageName + "/main."

+ Def.EXTENSION_FILE_VERSION + "." + thePackageName + ".obb";



시작합니다.

아래의 두개의 프로젝트를 import한다 

D:\adt-bundle-windows-x86_64\sdk\extras\google\play_apk_expansion\downloader_library

D:\adt-bundle-windows-x86_64\sdk\extras\google\play_apk_expansion\zip_file

downloader_library여기서 에러 나는데 library라이센스를 다시 정해 주면된다 


라이센스는 D:\adt-bundle-windows-x86_64\sdk\extras\google\play_licensing 여기 있습니다.


downloader_library,zip_file 둘을 작업 중인 프로젝트에서 프로젝트>안드로이드>library에 add한다 



AndroidManifest.xml

         <service

            android:name="com.home.test.s1.ExpansionFile.ExpansionFileDownloaderService"/>

        <receiver

            android:name="com.home.test.s1.ExpansionFile.ExpansionFileAlarmReceiver" />


이건 그냥 내가 쓴건데 이중에 뭐가 필요한건지 모르겠네 ...

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

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

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

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

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

    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />

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

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

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




두개의 파일


ExpansionFileAlarmReceiver.java

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.pm.PackageManager.NameNotFoundException;

import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;

public class ExpansionFileAlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

try {

DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent,

ExpansionFileDownloaderService.class);

} catch (NameNotFoundException e) {


}

}

}


ExpansionFileDownloaderService.java
import com.google.android.vending.expansion.downloader.impl.DownloaderService;
public class ExpansionFileDownloaderService extends DownloaderService {
//렌덤 숫자 20개 (byte) 아무렇게나 바이트 숫자 넣으세요
private static final byte[] SALT = new byte[]{
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9};
@Override
public String getAlarmReceiverClassName() {
// TODO Auto-generated method stub
return ExpansionFileDownloaderService.class.getName();
}
@Override
public String getPublicKey() {
// TODO Auto-generated method stub
    //이건 MIIBIjANBgkq...... 요래 시작하는 긴거 알지요 ? 안드로이드 콘솔에서 해당 앱눌러서 publickey
return getResources().getString(R.string.base64EncodedPublicKey);
}
@Override
public byte[] getSALT() {
// TODO Auto-generated method stub
return SALT;
}
}


요건 activity에서 기록하는것 
 Def.EXTENSION_FILE_VERSION 이건 확장 파일을 콘솔에 올렸을때의 앱버젼이다


public class IntroLogoActivity extends SActivity implements IDownloaderClient {
.
.
.
.

String mainFileName = Helpers.getExpansionAPKFileName(this, true, Def.EXTENSION_FILE_VERSION);
Log.e(Constants.TAG, "CRC does not match for entry: ");

if (!Helpers.doesFileExist(this, mainFileName,
Integer.parseInt(getResources().getString(R.string.extendfilesize)), false)) {

mExtensionFrame.setVisibility(View.VISIBLE);
Intent launcher = getIntent();
Intent fromNotification = new Intent(this, getClass());
fromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
fromNotification.setAction(launcher.getAction());
if (launcher.getCategories() != null) {
for (String cat : launcher.getCategories()) {
fromNotification.addCategory(cat);
}
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 279912, fromNotification,
PendingIntent.FLAG_UPDATE_CURRENT);
try {
// Start the download
int result = DownloaderClientMarshaller.startDownloadServiceIfRequired(this, pendingIntent,
ExpansionFileDownloaderService.class);
Log.i("AA", "DownloaderClientMarshaller result => " + result);
if (DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED != result) {
// implement Downloading UI.
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
ExpansionFileDownloaderService.class);
ToastS.makeText(mToast, this, "파일을 다운로드 중입니다.");
}
} catch (NameNotFoundException e) {
Log.e("apk-expansion-files", "NameNotFoundException occurred. " + e.getMessage(), e);
}
} else {
CallNext();
}

.
.
.
.

@Override
protected void onResume() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onResume();
}
@Override
protected void onStop() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.disconnect(this);
}
super.onStop();
}



@Override
public void onDownloadProgress(DownloadProgressInfo progress) {
// TODO Auto-generated method stub
//다운로드 진행 상황 보여줄려고 하는 ui입니다 입맞에 맞게 작성하시면됩니다 .
//일단 값들은 찍어 보세요 
progress.mOverallTotal = progress.mOverallTotal;
mExtenstionProgress.setMax((int) (progress.mOverallTotal >> 8));
mExtenstionProgress.setProgress((int) (progress.mOverallProgress >> 8));
mExtensionCur.setText(Long.toString(progress.mOverallProgress * 100 / progress.mOverallTotal) + "%");
mExtensionMax.setText(Helpers.getDownloadProgressString(progress.mOverallProgress, progress.mOverallTotal));
}

@Override
public void onDownloadStateChanged(int newState) {
// TODO Auto-generated method stub
Log.i("AA", "in onDownloadStateChanged, newState=" + newState);
boolean showDashboard = true;

boolean fAppFinish = false;
//상황에 맞게 작업들을 넣어줘야합니다.
switch (newState) {
case STATE_COMPLETED:// The download was finished
showDashboard = false;
CallNext();
break;
case STATE_IDLE:
Log.i("AA", "in onDownloadStateChanged, STATE_IDLE");
break;
case STATE_FETCHING_URL:
showDashboard = true;
Log.i("AA", "in onDownloadStateChanged, STATE_FETCHING_URL");
break;
case STATE_CONNECTING:
showDashboard = true;
Log.i("AA", "in onDownloadStateChanged, STATE_CONNECTING");
break;
case STATE_DOWNLOADING:
showDashboard = true;
Log.i("AA", "in onDownloadStateChanged, STATE_DOWNLOADING");
break;
case STATE_PAUSED_NETWORK_UNAVAILABLE:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_NETWORK_UNAVAILABLE");
break;
case STATE_PAUSED_BY_REQUEST:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_BY_REQUEST");
break;
case STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION");
break;
case STATE_PAUSED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_NEED_CELLULAR_PERMISSION");
break;
case STATE_PAUSED_WIFI_DISABLED:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_WIFI_DISABLED");
break;
case STATE_PAUSED_NEED_WIFI:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_NEED_WIFI");
break;
case STATE_PAUSED_ROAMING:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_ROAMING");
break;
case STATE_PAUSED_NETWORK_SETUP_FAILURE:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_NETWORK_SETUP_FAILURE");
break;
case STATE_PAUSED_SDCARD_UNAVAILABLE:
Log.i("AA", "in onDownloadStateChanged, STATE_PAUSED_SDCARD_UNAVAILABLE");
break;
case STATE_FAILED_UNLICENSED:
ToastS.makeText(mToast, this, "라이센스 검사에 실패 했습니다.\n앱을 종료합니다.");
fAppFinish = true;
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_FAILED_UNLICENSED");
break;
case STATE_FAILED_FETCHING_URL:
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_FAILED_FETCHING_URL");
break;
case STATE_FAILED_SDCARD_FULL:
ToastS.makeText(mToast, this, "저장 공간이 부족합니다.");
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_FAILED_SDCARD_FULL");
break;
case STATE_FAILED_CANCELED:
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_FAILED_CANCELED");
break;
case STATE_FAILED:
showDashboard = false;
Log.i("AA", "in onDownloadStateChanged, STATE_FAILED");
break;
}
int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
if (mExtensionFrame.getVisibility() != newDashboardVisibility) {
mExtensionFrame.setVisibility(newDashboardVisibility);
}

if (fAppFinish) {
finish();
}

}

@Override
public void onServiceConnected(Messenger m) {
// TODO Auto-generated method stub
Log.i("AA", "Download started...");
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);

mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());

}


.
.
.
요건 파일 가져오는거 2가지 방법
public AssetFileDescriptor getAssetFileDescriptor(String filePath) {
PackageManager manager = this.getPackageManager();
PackageInfo info;
try {
info = manager.getPackageInfo(this.getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
return null;
}
String thePackageName = this.getPackageName();
// int thePackageVer = info.versionCode;

String zipFilePath = Environment.getExternalStorageDirectory() + "/Android/obb/" + thePackageName + "/main."
+ Def.EXTENSION_FILE_VERSION + "." + thePackageName + ".obb";
ZipResourceFile expansionFile = null;
AssetFileDescriptor afd = null;
try {
expansionFile = new ZipResourceFile(zipFilePath);

afd = expansionFile.getAssetFileDescriptor(filePath);
} catch (IOException e) {
e.printStackTrace();
}
return afd;
}

public InputStream getAssetFileInputStream(String filePath) {

PackageManager manager = this.getPackageManager();
PackageInfo info;
try {
info = manager.getPackageInfo(this.getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
return null;
}
String thePackageName = this.getPackageName();
// int thePackageVer = info.versionCode;

String zipFilePath = Environment.getExternalStorageDirectory() + "/Android/obb/" + thePackageName + "/main."
+ Def.EXTENSION_FILE_VERSION + "." + thePackageName + ".obb";
ZipResourceFile expansionFile = null;
InputStream is = null;
try {
expansionFile = new ZipResourceFile(zipFilePath);
is = expansionFile.getInputStream(filePath);

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



라이센스 에러 나고 페치 url 실패 나고 하는데요 
확장 파일 버젼 잘 맞추고 사이닝된 apk파일과 콘솔에 올린 버젼이 같으면 됩니다.

일단은 저는 알파테스트로 apk를 올리고 거기다 확장 파일 올리고 
다음 부터는 싸이닝된 apk파일 만들어서 폰에 넣고 설치하고를 반복 하면서 테스트 했습니다.

그런데 확장 파일콘솔에 올리고 난뒤에 디버깅으로 앱 설치해도 확장 파일 다운로드가 되네요 디버깅이 더 쉬워 졌어요


처음에 콘솔에 올리고 언제 업데이트 되서 테스트 하나 막막했음 ....


'안드로이드' 카테고리의 다른 글

cardslib  (0) 2014.04.30
안드로이드 소스 다운로드  (0) 2014.04.16
안드로이드 화학기호 수학기호의 승 표시  (0) 2014.02.27
구글 영수증 코드 확인 하는 방법  (0) 2014.02.12
ANDROID LISTVIEW GET HEIGHT  (0) 2014.01.15
posted by 욱이다
2014. 2. 27. 13:43 안드로이드


TextView tvInfo;

tvInfo.setText(Html.fromHtml("SO<sub><small>4</small></sub><sup><small>2</small></sup>    SO<sub>4</sub><sup>2</sup>"));


아 .. 씸플하다 




posted by 욱이다
2014. 2. 14. 13:43 카테고리 없음




Activity.java 부분


googleBilling mGoogle = new googleBilling(this, this);

mGoogle.setOnGoogleListener(this);


protected void onActivityResult(int requestCode, int resultCode, Intent data) {


// TODO Auto-generated method stub

if (mGoogle.onActivityResult(requestCode, resultCode, data))

super.onActivityResult(requestCode, resultCode, data);

}



////////////////////////////////////////////////////////////////////////////////


public class googleBilling {

IabHelper mHelper;

String payID;

String base64EncodedPublicKey;

int ActivityResultCode = 2799;


String LogTag = "billing";

Context mContext;

Activity mAct;

onGoogleBillingListener mListener;


public interface onGoogleBillingListener {

public void startLoading();


public void endLoading();


public void sendMessage(String Message);


public void complete(String ItemType, String jsonPurchaseInfo, String signature);


}


public googleBilling(Context context, Activity act) {

mContext = context;

mAct = act;

payID = mContext.getResources().getString(R.string.payID);

base64EncodedPublicKey = mContext.getResources().getString(R.string.base64EncodedPublicKey);


mHelper = new IabHelper(mContext, base64EncodedPublicKey);

mHelper.enableDebugLogging(true); // 디버깅 모드시 true

mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

@Override

public void onIabSetupFinished(IabResult result) {

if (!result.isSuccess()) {

// 초기화 실패 하면 여기로 들오 옴

Log.d(LogTag, "초기화 실패 " + result.getMessage());

if (mListener != null)

mListener.sendMessage("구글 결재 초기화를 실패 했습니다.\n종료합니다.");

mAct.finish();

return;

}

Log.d(LogTag, "구매 정보를 설정하고 받아 옵니다");


mHelper.queryInventoryAsync(mGotInventoryListener);

}

});

}


IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {

@Override

public void onQueryInventoryFinished(IabResult result, Inventory inv) {

// TODO

if (result.isFailure()) {

Log.d(LogTag, "구매 한적 있는지 확인 실패" + result.getMessage());

return; // handle error

}

Purchase checkPurchase = inv.getPurchase(payID);

if (checkPurchase == null)

Log.d(LogTag, "구매 한적이 없습니다.");

else

Log.d(LogTag, "구매 한적이 있습니다.");


// 구매한 적이있으면 일단은 구매 정보를 지운다 어짜피 서버에 기록되어있으니깐

if (checkPurchase != null && verifyDeveloperPayload(checkPurchase)) {

Log.d(LogTag, "We have gas. Consuming it.");

mHelper.consumeAsync(inv.getPurchase(payID), mConsumeFinishedListener);

return;

}

}

};


public void BuyItemClick() {

Log.d(LogTag, "아이템 구매 클릭 시작");

Log.d(LogTag, "mListener " + mListener);

if (mListener != null)

mListener.startLoading();

mHelper.launchPurchaseFlow(mAct, payID, ActivityResultCode, mPurchaseFinishedListener);


}


// 아이템 구입이 되면 진행되는 콜백

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {


@Override

public void onIabPurchaseFinished(IabResult result, Purchase info) {


if (result.isFailure()) {

if (mListener != null)

mListener.sendMessage("구입에 실패 했습니다.");

return;

}


mHelper.consumeAsync(info, mConsumeFinishedListener);

Log.d(LogTag, "구입 성공.");

// if (info.getSku().equals(payID)) {

//

// } else {

// Log.d(LogTag, "구입 성공 했으나 틀림 " + info.getSku() + "  " + payID);

// paymentDataInit();

// }

}

};

// 아이템 과금이 완료 되었을때 호출 되는 부분 입니다.

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {

@Override

public void onConsumeFinished(Purchase purchase, IabResult result) {

paymentDataInit();

// TODO

if (result.isSuccess()) {

// 성공

if (mListener != null)

mListener.complete(purchase.getItemType(), purchase.getOriginalJson(), purchase.getSignature());

Log.d(LogTag, "결제 과금에 성공 " + mListener);


Log.d(LogTag, "OrderID : " + purchase.getOrderId());

Log.d(LogTag, "PackageName : " + purchase.getPackageName());

Log.d(LogTag, "PurchaseTime :" + purchase.getPurchaseTime());

Log.d(LogTag, "PurchaseState : " + purchase.getPurchaseState());

Log.d(LogTag, "developerPayload : " + purchase.getDeveloperPayload());

Log.d(LogTag, "PurchaseToken : " + purchase.getToken());

Log.d(LogTag, "ItemType : " + purchase.getItemType());

Log.d(LogTag, "Siginature : " + purchase.getSignature());

Log.d(LogTag, "purchaseInfo : " + purchase.toString());

} else {

Log.d(LogTag, "결제 과금에 실패");

Log.d(LogTag, "OrderID : " + purchase.getOrderId());

Log.d(LogTag, "PackageName : " + purchase.getPackageName());

Log.d(LogTag, "PurchaseTime :" + purchase.getPurchaseTime());

Log.d(LogTag, "PurchaseState : " + purchase.getPurchaseState());

Log.d(LogTag, "developerPayload : " + purchase.getDeveloperPayload());

Log.d(LogTag, "PurchaseToken : " + purchase.getToken());

Log.d(LogTag, "ItemType : " + purchase.getItemType());

Log.d(LogTag, "Siginature : " + purchase.getSignature());

Log.d(LogTag, "purchaseInfo : " + purchase.toString());

}

}


};


public boolean onActivityResult(int requestCode, int resultCode, Intent data) {

boolean fGoNextLogic = false;


Log.d(LogTag, "onActivityResult(" + requestCode + "," + resultCode + "," + data);

if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {

fGoNextLogic = true;

// super.onActivityResult(requestCode, resultCode, data);

} else {

Log.d(LogTag, "onActivityResult handled by IABUtil.");

if (mListener != null)

mListener.endLoading();

fGoNextLogic = false;

}

return fGoNextLogic;

}


public void release() {

Log.d(LogTag, "아이템 구매 종료 (초기화)");

if (mHelper != null)

mHelper.dispose();

mHelper = null;

}



public void paymentDataInit() {

endPay();

}



public void endPay() {

// 로딩 스톱

if (mListener != null)

mListener.startLoading();

}


public void setOnGoogleListener(onGoogleBillingListener listener) {

mListener = listener;

}


/** Verifies the developer payload of a purchase. */

boolean verifyDeveloperPayload(Purchase p) {

if (p == null)

return false;

String payload = p.getDeveloperPayload();


/*

* TODO: verify that the developer payload of the purchase is correct.

* It will be the same one that you sent when initiating the purchase.

* WARNING: Locally generating a random string when starting a purchase

* and verifying it here might seem like a good approach, but this will

* fail in the case where the user purchases an item on one device and

* then uses your app on a different device, because on the other device

* you will not have access to the random string you originally

* generated.

* So a good developer payload has these characteristics:

* 1. If two different users purchase an item, the payload is different

* between them, so that one user's purchase can't be replayed to

* another user.

* 2. The payload must be such that you can verify it even when the app

* wasn't the one who initiated the purchase flow (so that items

* purchased by the user on one device work on other devices owned by

* the user).

* Using your own server to store and verify developer payloads across

* app installations is recommended.

*/


return true;

}


}



posted by 욱이다
2014. 2. 12. 17:39 안드로이드

구글 영수증 확인 코드 서버용이네


안드로이드 sdk에 위치해있다

D:\adt-bundle-windows-x86_64\sdk\sources\android-19\java\security\Security.java


/*

 *  Licensed to the Apache Software Foundation (ASF) under one or more

 *  contributor license agreements.  See the NOTICE file distributed with

 *  this work for additional information regarding copyright ownership.

 *  The ASF licenses this file to You under the Apache License, Version 2.0

 *  (the "License"); you may not use this file except in compliance with

 *  the License.  You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 *  Unless required by applicable law or agreed to in writing, software

 *  distributed under the License is distributed on an "AS IS" BASIS,

 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 *  See the License for the specific language governing permissions and

 *  limitations under the License.

 */


package java.security;


import java.io.BufferedInputStream;

import java.io.InputStream;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Properties;

import java.util.Set;

import org.apache.harmony.security.fortress.Engine;

import org.apache.harmony.security.fortress.SecurityAccess;

import org.apache.harmony.security.fortress.Services;


/**

 * {@code Security} is the central class in the Java Security API. It manages

 * the list of security {@code Provider} that have been installed into this

 * runtime environment.

 */

public final class Security {


    // Security properties

    private static final Properties secprops = new Properties();


    // static initialization

    // - load security properties files

    // - load statically registered providers

    // - if no provider description file found then load default providers

    static {

        boolean loaded = false;

        try {

            InputStream configStream = Security.class.getResourceAsStream("security.properties");

            InputStream input = new BufferedInputStream(configStream);

            secprops.load(input);

            loaded = true;

            configStream.close();

        } catch (Exception ex) {

            System.logE("Could not load 'security.properties'", ex);

        }

        if (!loaded) {

            registerDefaultProviders();

        }

        Engine.door = new SecurityDoor();

    }


    /**

     * This class can't be instantiated.

     */

    private Security() {

    }


    // Register default providers

    private static void registerDefaultProviders() {

        secprops.put("security.provider.1", "com.android.org.conscrypt.OpenSSLProvider");

        secprops.put("security.provider.2", "org.apache.harmony.security.provider.cert.DRLCertFactory");

        secprops.put("security.provider.3", "com.android.org.bouncycastle.jce.provider.BouncyCastleProvider");

        secprops.put("security.provider.4", "org.apache.harmony.security.provider.crypto.CryptoProvider");

        secprops.put("security.provider.5", "com.android.org.conscrypt.JSSEProvider");

    }


    /**

     * Returns value for the specified algorithm with the specified name.

     *

     * @param algName

     *            the name of the algorithm.

     * @param propName

     *            the name of the property.

     * @return value of the property.

     * @deprecated Use {@link AlgorithmParameters} and {@link KeyFactory} instead.

     */

    @Deprecated

    public static String getAlgorithmProperty(String algName, String propName) {

        if (algName == null || propName == null) {

            return null;

        }

        String prop = "Alg." + propName + "." + algName;

        Provider[] providers = getProviders();

        for (Provider provider : providers) {

            for (Enumeration e = provider.propertyNames(); e.hasMoreElements(); ) {

                String propertyName = (String) e.nextElement();

                if (propertyName.equalsIgnoreCase(prop)) {

                    return provider.getProperty(propertyName);

                }

            }

        }

        return null;

    }


    /**

     * Insert the given {@code Provider} at the specified {@code position}. The

     * positions define the preference order in which providers are searched for

     * requested algorithms.

     *

     * @param provider

     *            the provider to insert.

     * @param position

     *            the position (starting from 1).

     * @return the actual position or {@code -1} if the given {@code provider}

     *         was already in the list. The actual position may be different

     *         from the desired position.

     */

    public static synchronized int insertProviderAt(Provider provider, int position) {

        // check that provider is not already

        // installed, else return -1; if (position <1) or (position > max

        // position) position = max position + 1; insert provider, shift up

        // one position for next providers; Note: The position is 1-based

        if (getProvider(provider.getName()) != null) {

            return -1;

        }

        int result = Services.insertProviderAt(provider, position);

        renumProviders();

        return result;

    }


    /**

     * Adds the given {@code provider} to the collection of providers at the

     * next available position.

     *

     * @param provider

     *            the provider to be added.

     * @return the actual position or {@code -1} if the given {@code provider}

     *         was already in the list.

     */

    public static int addProvider(Provider provider) {

        return insertProviderAt(provider, 0);

    }


    /**

     * Removes the {@code Provider} with the specified name form the collection

     * of providers. If the the {@code Provider} with the specified name is

     * removed, all provider at a greater position are shifted down one

     * position.

     *

     * <p>Returns silently if {@code name} is {@code null} or no provider with the

     * specified name is installed.

     *

     * @param name

     *            the name of the provider to remove.

     */

    public static synchronized void removeProvider(String name) {

        // It is not clear from spec.:

        // 1. if name is null, should we checkSecurityAccess or not?

        //    throw SecurityException or not?

        // 2. as 1 but provider is not installed

        // 3. behavior if name is empty string?


        Provider p;

        if ((name == null) || (name.length() == 0)) {

            return;

        }

        p = getProvider(name);

        if (p == null) {

            return;

        }

        Services.removeProvider(p.getProviderNumber());

        renumProviders();

        p.setProviderNumber(-1);

    }


    /**

     * Returns an array containing all installed providers. The providers are

     * ordered according their preference order.

     *

     * @return an array containing all installed providers.

     */

    public static synchronized Provider[] getProviders() {

        return Services.getProviders();

    }


    /**

     * Returns the {@code Provider} with the specified name. Returns {@code

     * null} if name is {@code null} or no provider with the specified name is

     * installed.

     *

     * @param name

     *            the name of the requested provider.

     * @return the provider with the specified name, maybe {@code null}.

     */

    public static synchronized Provider getProvider(String name) {

        return Services.getProvider(name);

    }


    /**

     * Returns the array of providers which meet the user supplied string

     * filter. The specified filter must be supplied in one of two formats:

     * <nl>

     * <li> CRYPTO_SERVICE_NAME.ALGORITHM_OR_TYPE

     * <p>

     * (for example: "MessageDigest.SHA")

     * <li> CRYPTO_SERVICE_NAME.ALGORITHM_OR_TYPE

     * ATTR_NAME:ATTR_VALUE

     * <p>

     * (for example: "Signature.MD2withRSA KeySize:512")

     * </nl>

     *

     * @param filter

     *            case-insensitive filter.

     * @return the providers which meet the user supplied string filter {@code

     *         filter}. A {@code null} value signifies that none of the

     *         installed providers meets the filter specification.

     * @throws InvalidParameterException

     *             if an unusable filter is supplied.

     * @throws NullPointerException

     *             if {@code filter} is {@code null}.

     */

    public static Provider[] getProviders(String filter) {

        if (filter == null) {

            throw new NullPointerException("filter == null");

        }

        if (filter.length() == 0) {

            throw new InvalidParameterException();

        }

        HashMap<String, String> hm = new HashMap<String, String>();

        int i = filter.indexOf(':');

        if ((i == filter.length() - 1) || (i == 0)) {

            throw new InvalidParameterException();

        }

        if (i < 1) {

            hm.put(filter, "");

        } else {

            hm.put(filter.substring(0, i), filter.substring(i + 1));

        }

        return getProviders(hm);

    }


    /**

     * Returns the array of providers which meet the user supplied set of

     * filters. The filter must be supplied in one of two formats:

     * <nl>

     * <li> CRYPTO_SERVICE_NAME.ALGORITHM_OR_TYPE

     * <p>

     * for example: "MessageDigest.SHA" The value associated with the key must

     * be an empty string. <li> CRYPTO_SERVICE_NAME.ALGORITHM_OR_TYPE

     * ATTR_NAME:ATTR_VALUE

     * <p>

     * for example: "Signature.MD2withRSA KeySize:512" where "KeySize:512" is

     * the value of the filter map entry.

     * </nl>

     *

     * @param filter

     *            case-insensitive filter.

     * @return the providers which meet the user supplied string filter {@code

     *         filter}. A {@code null} value signifies that none of the

     *         installed providers meets the filter specification.

     * @throws InvalidParameterException

     *             if an unusable filter is supplied.

     * @throws NullPointerException

     *             if {@code filter} is {@code null}.

     */

    public static synchronized Provider[] getProviders(Map<String,String> filter) {

        if (filter == null) {

            throw new NullPointerException("filter == null");

        }

        if (filter.isEmpty()) {

            return null;

        }

        java.util.List<Provider> result = Services.getProvidersList();

        Set<Entry<String, String>> keys = filter.entrySet();

        Map.Entry<String, String> entry;

        for (Iterator<Entry<String, String>> it = keys.iterator(); it.hasNext();) {

            entry = it.next();

            String key = entry.getKey();

            String val = entry.getValue();

            String attribute = null;

            int i = key.indexOf(' ');

            int j = key.indexOf('.');

            if (j == -1) {

                throw new InvalidParameterException();

            }

            if (i == -1) { // <crypto_service>.<algorithm_or_type>

                if (val.length() != 0) {

                    throw new InvalidParameterException();

                }

            } else { // <crypto_service>.<algorithm_or_type> <attribute_name>

                if (val.length() == 0) {

                    throw new InvalidParameterException();

                }

                attribute = key.substring(i + 1);

                if (attribute.trim().length() == 0) {

                    throw new InvalidParameterException();

                }

                key = key.substring(0, i);

            }

            String serv = key.substring(0, j);

            String alg = key.substring(j + 1);

            if (serv.length() == 0 || alg.length() == 0) {

                throw new InvalidParameterException();

            }

            Provider p;

            for (int k = 0; k < result.size(); k++) {

                try {

                    p = result.get(k);

                } catch (IndexOutOfBoundsException e) {

                    break;

                }

                if (!p.implementsAlg(serv, alg, attribute, val)) {

                    result.remove(p);

                    k--;

                }

            }

        }

        if (result.size() > 0) {

            return result.toArray(new Provider[result.size()]);

        }

        return null;

    }


    /**

     * Returns the value of the security property named by the argument.

     *

     * @param key

     *            the name of the requested security property.

     * @return the value of the security property.

     */

    public static String getProperty(String key) {

        if (key == null) {

            throw new NullPointerException("key == null");

        }

        String property = secprops.getProperty(key);

        if (property != null) {

            property = property.trim();

        }

        return property;

    }


    /**

     * Sets the value of the specified security property.

     */

    public static void setProperty(String key, String value) {

        secprops.put(key, value);

    }


    /**

     * Returns a {@code Set} of all registered algorithms for the specified

     * cryptographic service. {@code "Signature"}, {@code "Cipher"} and {@code

     * "KeyStore"} are examples for such kind of services.

     *

     * @param serviceName

     *            the case-insensitive name of the service.

     * @return a {@code Set} of all registered algorithms for the specified

     *         cryptographic service, or an empty {@code Set} if {@code

     *         serviceName} is {@code null} or if no registered provider

     *         provides the requested service.

     */

    public static Set<String> getAlgorithms(String serviceName) {

        Set<String> result = new HashSet<String>();

        // compatibility with RI

        if (serviceName == null) {

            return result;

        }

        for (Provider provider : getProviders()) {

            for (Provider.Service service: provider.getServices()) {

                if (service.getType().equalsIgnoreCase(serviceName)) {

                    result.add(service.getAlgorithm());

                }

            }

        }

        return result;

    }


    /**

     *

     * Update sequence numbers of all providers.

     *

     */

    private static void renumProviders() {

        Provider[] p = Services.getProviders();

        for (int i = 0; i < p.length; i++) {

            p[i].setProviderNumber(i + 1);

        }

    }


    private static class SecurityDoor implements SecurityAccess {

        // Access to Security.renumProviders()

        public void renumProviders() {

            Security.renumProviders();

        }


        //  Access to Security.getAliases()

        public List<String> getAliases(Provider.Service s) {

            return s.getAliases();

        }


        // Access to Provider.getService()

        public Provider.Service getService(Provider p, String type) {

            return p.getService(type);

        }

    }

}



posted by 욱이다
2014. 1. 15. 16:50 안드로이드

안드로이드 가변적인 LISTVIEW의 높이에 맞게 레이아웃을 잡을려고 할때 쓰나 



private int getListViewHeight(ListView list) {

 ListAdapter adapter = list.getAdapter();

 int listviewHeight = 0;

 list.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

 listviewHeight = list.getMeasuredHeight() * adapter.getCount() + (adapter.getCount() * list.getDividerHeight());

 return listviewHeight;

 }




mListView_ExamUnitList.invalidate();


int listHeight = getListViewHeight(mListView_ExamUnitList);

RelativeLayout.LayoutParams params2 =  new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,listHeight);

params2.addRule(RelativeLayout.BELOW,R.id.usersetting_spinner);

params2.setMargins(Util.dpToPx(getResources(), 10), Util.dpToPx(getResources(), 10), Util.dpToPx(getResources(), 10), 0);

mListView_ExamUnitList.setLayoutParams(params2);






요건 DP를 픽셀로 바꾸는 것

public static int dpToPx(Resources res, int dp) {

return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());

}

posted by 욱이다
2014. 1. 11. 10:19 안드로이드

 translateAnimation후 click이벤트 먹게 하는 방법


package com.paran.animation.demo.app.animation;


import android.app.Activity;

import android.content.Context;

import android.graphics.Rect;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.Animation;

import android.view.animation.Animation.AnimationListener;

import android.view.animation.AnimationSet;

import android.view.animation.AnimationUtils;

import android.view.animation.RotateAnimation;

import android.view.animation.TranslateAnimation;

import android.widget.Button;

import android.widget.FrameLayout;

import android.widget.FrameLayout.LayoutParams;

import android.widget.Toast;


public class ShotButton extends Activity

{


FrameLayout Root;

Button ShotBtn, BulletBtn[];



@Override

protected void onCreate(Bundle savedInstanceState)

{

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

Root = new FrameLayout(this);


BulletBtn = new Button[5];

for (int i = 0; i < 5; i++)

{

BulletBtn[i] = new Button(this);

BulletBtn[i].setText("" + i);

final int index = i;

BulletBtn[i].setOnClickListener(new OnClickListener()

{

@Override

public void onClick(View v)

{

// TODO Auto-generated method stub

Toast.makeText(ShotButton.this, BulletBtn[index].getText(), Toast.LENGTH_SHORT).show();

}

});

Root.addView(BulletBtn[i], new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT));

}


ShotBtn = new Button(this);

ShotBtn.setText("START");

ShotBtn.setOnClickListener(new OnClickListener()

{

@Override

public void onClick(View v)

{

// TODO Auto-generated method stub

for (int i = 0; i < 5; i++)

{

final int index = i;

final int finalx = 100 * i + 50, finaly = 500;

AnimationSet animation = new AnimationSet(false);

RotateAnimation AniRotation = new RotateAnimation(0, 720);

AniRotation.setDuration(400);

TranslateAnimation AniTrans = new TranslateAnimation(0, finalx, 0, finaly);

AniTrans.setDuration(400);

AniTrans.setInterpolator(AnimationUtils.loadInterpolator(ShotButton.this,

android.R.anim.overshoot_interpolator));

AniTrans.setStartOffset(20 * i);


// animation.addAnimation(AniRotation);

animation.addAnimation(AniTrans);

animation.setFillAfter(true);//이거 하면 위치에 가던데 아래의 리스너로 setmargins하면 더 아래로 내려 가버리더라

// animation.setFillEnabled(true);


BulletBtn[i].startAnimation(animation);


animation.setAnimationListener(new AnimationListener()

{

@Override

public void onAnimationStart(Animation animation)

{

// TODO Auto-generated method stub

//처음의 버튼 위치 

FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(BulletBtn[index]

.getLayoutParams());

lp.setMargins(0, 0, 0, 0);

BulletBtn[index].setLayoutParams(lp);

BulletBtn[index].requestLayout();

fAniEnd = false;

}


@Override

public void onAnimationRepeat(Animation animation)

{

// TODO Auto-generated method stub


}


@Override

public void onAnimationEnd(Animation animation)

{

// TODO Auto-generated method stub

// if (animation.equals(BulletBtn[index].getAnimation()))

{

//애니가 끝났을때 버튼의 위치 

// FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(BulletBtn[index]

// .getLayoutParams());

// Log.i("aa","Margin "+lp.leftMargin+" "+lp.rightMargin+ " "+lp.topMargin+" "+lp.bottomMargin);

// lp.setMargins(finalx, finaly, 0, 0);

// BulletBtn[index].setLayoutParams(lp);

// BulletBtn[index].requestLayout();


BulletBtn[index].postDelayed(new Runnable()

{

@Override

public void run()

{

// TODO Auto-generated method stub



FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(BulletBtn[index]

.getLayoutParams());


lp.setMargins(finalx, finaly, 0, 0);

BulletBtn[index].setLayoutParams(lp);

BulletBtn[index].requestLayout();


BulletBtn[index].clearAnimation();

}

}, 0);

}


}

});

}

}

});

Root.addView(ShotBtn, new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));


setContentView(Root);

}


boolean fAniEnd = false;

}



posted by 욱이다
2014. 1. 9. 22:57 JAVA

이미지 가꼬가서 쓰는거 아닌가 해서 바로 못보게 해야겠는데 ...

뭐 딱히 방법도 없고 해서 .... 걍 섞어 보자 해서 



import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;


public class ChangerManager {

final int jumpsize[] = { 1, 3, 2, 0, 4 };


/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stu

ChangerManager cm = new ChangerManager(

"/Users/s/Documents/project_android/ImageChanger/img",

"/Users/s/Documents/project_android/ImageChanger/img_");

}


public ChangerManager(String getPath, String setPath) {

File fget = new File(getPath);

File fset = new File(setPath);


String strGetList[] = fget.list();

for (int i = 0; i < strGetList.length; i++) {

byte buffer[] = getFileByte(new File(getPath + "/" + strGetList[i]));


int len = buffer.length / jumpsize.length;

///////////////////////////////////////이건 썩어서 저장

byte buf[] = new byte[buffer.length];

System.arraycopy(buffer, 0, buf, 0, buffer.length);

for (int j = 0; j < jumpsize.length; j++) {

int offset = jumpsize[j] / jumpsize.length;

System.arraycopy(buffer, len * j, buf, len * jumpsize[j], len);

}

setFileByte(buf, new File(setPath + "/" + strGetList[i]));

///////////////////////////////////////이건 썩은걸 다시 원상 복구 해본거

byte buf2[] = new byte[buf.length];

System.arraycopy(buf, 0, buf2, 0, buf.length);

for (int j = 0; j < jumpsize.length; j++) {

int offset = jumpsize[j] / jumpsize.length;

System.arraycopy(buf, len * jumpsize[j], buf2, len * j, len);

}

setFileByte(buf2, new File(setPath + "/_" + strGetList[i]));

}


}


public void getFileCheck(byte buff[], File f)

{

}

public void setFileByte(byte buff[], File f) {

FileOutputStream fos = null;

try {

fos = new FileOutputStream(f);

fos.write(buff);

} catch (Exception e) {


} finally {

try {

if (fos != null)

fos.close();

} catch (Exception e) {


}

}

}


public byte[] getFileByte(File f) {

long length = f.length();

byte buffer[] = new byte[(int) length];

FileInputStream fis = null;

try {

fis = new FileInputStream(f);

fis.read(buffer);

} catch (Exception e) {


} finally {

try {

if (fis != null)

fis.close();

} catch (Exception e) {


}

}

return buffer;

}

}

posted by 욱이다
prev 1 2 3 4 5 6 7 ··· 16 next