Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Tuesday, July 7, 2015

Make Intene Action_View receiver

This is the way to make my app would be exposed to other app when clicking some file.

reference by developer site
http://developer.android.com/training/sharing/receive.html


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.example.viewer;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

import com.example.com.example.viewer.R;

public class MainActivity extends Activity{

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  
  File file = new File(Environment.getExternalStorageDirectory() + "/download/shared.txt");
    Toast.makeText(getApplication(), "lenth " + file.length(), 0).show();

      Toast.makeText(getApplication(), "is deleted? " + file.delete(), 0).show();
    
     // Get intent, action and MIME type
     Intent intent = getIntent();
     String action = intent.getAction();
     String type = intent.getType();
     Toast.makeText(getApplication(), "action" + action +" : type " + type, 1).show();
     if (Intent.ACTION_VIEW.equals(action) && type != null) {
         if ("text/plain".equals(type)) {
             handleSendText(intent); // Handle text being sent
         } else if (type.startsWith("image/")) {
             handleSendImage(intent); // Handle single image being sent
         }
     } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
         if (type.startsWith("image/")) {
             handleSendMultipleImages(intent); // Handle multiple images being sent
         }
     } else {
         // Handle other intents, such as being started from the home screen
     }
 }

 void handleSendText(Intent intent) {
     String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
     
     Uri uri= intent.getData();
     Toast.makeText(getApplication(), "pa " + uri.getPath(), 1).show();
     
     
     File file = new File(uri.getPath());
     
     Toast.makeText(getApplication(), "lenth " + file.length(), 0).show();

     
     Toast.makeText(getApplication(), "is deleted? " + file.delete(), 0).show();
     
     Toast.makeText(getApplication(), "lenth " + new File(uri.getPath()).length(), 0).show();
     
     
     
     Toast.makeText(getApplication(), "ajdidjdi" + sharedText, 1).show();
     Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
     if (imageUri != null) {
      String st = imageUri.getPath();
      //
      Toast.makeText(getApplication(), "" + st, 1).show();
     }
     
     if (sharedText != null) {
      // Update UI to reflect text being shared
      
      Toast.makeText(getApplication(), "" + sharedText, 1).show();
     }
 }

 void handleSendImage(Intent intent) {
     Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
     if (imageUri != null) {
         // Update UI to reflect image being shared
     }
 }

 void handleSendMultipleImages(Intent intent) {
     ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
     if (imageUris != null) {
         // Update UI to reflect multiple images being shared
     }
 }
}



ManifestFile
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 <activity
            android:name="com.example.viewer.MainActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name" 
            android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>  
                <category android:name="android.intent.category.DEFAULT"/>  
                <category android:name="android.intent.category.BROWSABLE"/>  
            </intent-filter>         
            <intent-filter>
          <action android:name="android.intent.action.SEND" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="image/*" />
      </intent-filter>
      <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="text/plain" />
      </intent-filter>
      <intent-filter>
          <action android:name="android.intent.action.SEND_MULTIPLE" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="image/*" />
      </intent-filter>   
        </activity>

Tuesday, April 7, 2015

requestDisallowInterceptTouchEvent in android




The onInterceptTouchEvent() method is called whenever a touch event is detected on the surface of a ViewGroup,
including on the surface of its children. If onInterceptTouchEvent() returns true, the MotionEvent is intercepted,
meaning it will be not be passed on to the child, but rather to the onTouchEvent() method of the parent.


onInterceptTouchEvetn 순서
부모 -> 자식


onInterceptTouchEvent 이거는 자신 또는 자식의 터치가 발견되었을때 호출된다.
onInterceptTouchEvent true = 지금 위치에 스크롤을 사용하겠다.
                            false = 하위의 스크롤을 사용하겠다.





public abstract void (boolean disallowIntercept)

Added in API level 1
Called when a child does not want this parent and its ancestors to intercept touch events with onInterceptTouchEvent(MotionEvent).

This parent should pass this call onto its parents.
This parent must obey this request for the duration of the touch
(that is, only clear the flag after this parent has received an up or a cancel.

disallowIntercept True if the child does not want the parent to intercept touch events.

requestDisallowInterceptTouchEvent true : 상위 부모가 이벤트를 가져가지 못하게 한다.


ex)
mBannerPager.setOnTouchListener(new OnTouchListener() {
                              @Override
                              public boolean onTouch(View v, MotionEvent event) {
                                     
                                      switch (event.getActionMasked()) {
                                      case MotionEvent.ACTION_DOWN:
                                             mPager.requestDisallowInterceptTouchEvent(true);
                                             break;
                                      default:
                                             break;
                                      }
                                      return false;
                              }
                       });

Thursday, November 20, 2014

Tuesday, August 19, 2014

이름 자동완성 리스트

내 안드로이드폰 주소록 검색을 보게 되면
ㄱ만 쳐도 ㄱ을 포함하고 있는 사용자 이름을 다 검색하게 되어있다.
그것도 빠른 시간내에..

문뜩 이것을 따라 만들고 싶은 욕망이 치 솟아서 저번에 배운 한글 초성 + 중성 + 종성으로
나눠 따라 해보기로 했다.

1. 테이블을 
   name 
   name_index 필드를 만들었다.

  name 에는 홍길동이 들어가고
  name_index  에는 ㅎㅗㅇㄱㅣㄹㄷㅗㅇ 
이런식으로 초성중성조성으로 구분되어서 각각이 하나의 문자로 들어간다.

그러면 TextEdit box에서 정을 쳤을때
 " ㅈㅓㅇ "
을 like 검색을 하면 정에 관한 데이터들이 쭈루룩 올라온다.

약 500건의 데이터로 테스트를 했는데
실제 DB 에서 가져오는 시간은 0.01초 걸렸다.
 즉 10ms

많지 않는 내용의 값을 검색할때는 초성중성종성 을 넣은 란은 Like검색해서 가져오면
충분히 효율성이 있을 것이라고 생각한다.

물론 Server side의 입장을 다르게 될것이다
좀더 나은 효율성과 Perfomance 를 위해 

Lucene같은 라이브러리를 이용해도 되고
아니면 데이터베이스를 이용해도 되겠다.


Sunday, August 17, 2014

네이버 자동완성 기능 분석 - client side 편

처음 블로그를 시작해서 블로그의 내용은 왠만하면 영어로 작성하자고 다짐을 했다.
그런데 영어로 작성을 하다 보니깐 말도 잘안나오고 어려움이 많이 있었지만
여차 저차 해서 여태까지 블로그를 잘 작성해온것 같다.

오늘은 네이버 자동완성 기능에 대해서 포스팅을 하려고 한다.

만약에 우리가 "길찾기" 라는 단어를 검색하게 될 경우 네이버에서 어떠한 방법으로 API검색이 이루어지는지 확인해보자

길찾기

1. ㄱ
2. 기
3. 길

각각의 검색 결과
1. ㄱ

window.__jindo_callback._$3361_0({
"query" : ["ㄱ", "ㄱ"],
"answer" : [],
"nature" : [],
"items" : [
[["구글"],["괜찮아 사랑이야"],["고속도로교통상황"],["길찾기"],["교황"],["광복절"],["기상청"],["곽동연"],["공효진"],["그것이 알고싶다"],["군도"],["괜찮아 사랑이야 ost"],["기리보이"],["교황 방한일정"],["강동원"],["김소현"],["고고싱"],["김연아"],["교촌치킨"],["걸스데이"]],
[]
]
})

설명 : 초성을 검사해서 보여주고 싶은 순서대로 Item을 정렬해서 서버에서 내려주는 방식인가 보다. 프레임워크는 Naver에서 사용하고 있는 jindo라는것을 사용한다는것을 확인할 수 있다.

2. 기
window.__jindo_callback._$3361_0({
"query" : ["기", "기"],
"answer" : [],
"nature" : [],
"items" : [
[["길찾기"],["기상청"],["기리보이"],["김소현"],["김연아"],["김민교"],["김설진"],["김새론"],["김수현"],["김원중"],["김범수"],["김수로"],["김영희"],["김남길"],["기아자동차"],["김우빈"],["김민희"],["김태희"],["기분좋은날"],["김광석"]],
[]
]
})

설명 : 초성 중성까지 기 으로 시작하는 모든 단어중에 자동완성할 수 있는 단어들을 정렬해서 내려준다. Max검색어는 20개인가보다

3. 길
window.__jindo_callback._$3361_0({
"query" : ["길", "길"],
"answer" : [],
"nature" : [],
"items" : [
[["길찾기"],["기리보이"],["길구봉구"],["길"],["길거리야"],["기린"],["기리보이 안경"],["길찿기"],["기리보이 밖에비온다"],["길찾기 어플"],["기리보이 특별해"],["길병원"],["기리보이 안경벗은거"],["길림대"],["길상사"],["기리보이 탈락"],["길트"],["기름때 지우는법"],["길티크라운"],["길버트증후군"]],
[]
]
})

설명 : 여기서 특이한 사항은 한글이 초성 + 중성으로 이루어진 것과
        초성 + 중성 + 종성으로 이루어진 사항이 있는데 길이라는 검색을 했는데
        기린이라는 2단어의 검색결과도 나오는걸 확인 할 수 있다.
        즉 네이버의 자동완성 시스템은 종성의 자음을 다음글자의 초성으로 판단해서 1글자와 2자일 경우의 혼합의 데이터를 내려준다. 


Daum에서는
길이라는 단어를 검색하면 길의 마지막 종성의 ㄹ로 다음글자의 초성을 예측하는 검색을 하지 않는다.

Naver 와  Daum에서는 서로 다른 성격의 자동완성 검색을 하다고 판단 할 수 있다.


다시 네이버로 돌아와서

궁금증1 ?
ㄱ을 쳤다가 지우고 다시 ㄱ을 치면 통신이 재반복의 통신이 이루어지나?
크롬사이트로 네트워크를 보면서 확인해보았다.

네트워크가 이루어지는걸 확인해본 결과 한번 검색한 결과의 값은 재 요청을 하지 않으며
잠시 브라우져의 메모리에 캐쉬하는걸 확인할 수 있었다.

그러면 cookie에다가 저장하는지 확인해보았다.
cookie를 열어보니 검색결과에 대한 결과의 내용을 저장해놓지 않았다.
Localstorage, SessionStorage모두 결과의 대한 내용을 저장해놓았지 않았다.

즉 검색결과를 javascript단의 변수에 휘발성의 임시 메모리로 가지고 있는다는걸 알게되었다. (브라우져를 리프레쉬 하게 될 경우 데이터가 날아감)



Friday, August 8, 2014

Android Dialog With timeout

This would be good for you


package com.sanghwa.nettychatting.dialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;

public class CustomDialog {

static ProgressDialog pDialog =  null;

static int TIME_OUT =  5000;

static Handler handler = new Handler();

public static void showCustomDialog(Activity context){
if(pDialog == null){
pDialog  = new ProgressDialog(context);
pDialog.setCancelable(false);
pDialog.setMessage("loading..");
}

if(pDialog.isShowing()){
return;
}

pDialog.show();
handler.postDelayed(new Runnable() {

@Override
public void run() {
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}, TIME_OUT);


}

public static void close(){
if(pDialog == null){
return;
}
handler.postDelayed(new Runnable() {

@Override
public void run() {
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}, 0);
}
}

Friday, July 25, 2014

make service what is not stopping

I recommend this post is really good to restart service after stopping.

and there are two ways~! read it

http://ccdev.tistory.com/22

Sunday, May 11, 2014

Android clearly exit source

영어로 설명하려고 하다 보니깐 너무 어려워서 한글로 설명을 해야겠다.

내 현상 :
난 웹뷰를 사용하는 Application을 사용했는데 web에서 Browser의 accept-lanuguage의 값을 받아서 셋팅을 한다. 한국어 모드에서 어플리케이션을 종료하고 영어 모드로 변경하고 다시 어플을 실행했을때 웹뷰에서 예전의 값을 그대로 가지고 있는 현상이 발생되었다.
그 말은 즉, 어플리케이션이 정상적으로 완전 종료가 되지 않아서 프로세스가 완전 재실행되지 않고 웹뷰의 헤더값이 예전과 유지되는 현상이 있었다.

인터넷에서 찾아보니깐 어플리케이션을 종료하는 방법에는 여러가지가 있더라.
1. finish();

2. restartPackage

3. killBackgroundProcessor

4. killProcessor

5. System.exit(0)

마지막으로 아래와 같은 방법

테스트 결과 아래처럼 하는 방법이 제일 안전하고, 그리고 Webview의 내용이 정상적으로 재설정되었다.
아래 참조 링크 걸었는데 거기에 자세한 내용이 나온다.


final ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//stop running service inside current process. 
List<RunningServiceInfo> serviceList = am.getRunningServices(100);
for(RunningServiceInfo service : serviceList){
    if( service.pid == Process.myPid()){
        Intent stop = new Intent();
        stop.setComponent(service.service);
        stopService(stop);
    }
}
//move current task to background.
Intent launchHome = new Intent(Intent.ACTION_MAIN);
launchHome.addCategory(Intent.CATEGORY_DEFAULT); launchHome.addCategory(Intent.CATEGORY_HOME);
startActivity(launchHome);
//post delay runnable(waiting for home application launching) 
new Handler().postDelayed(new Runnable(){
    @Override public void run() {
        am.killBackgroundProcesses(getPackageName());
    }
}, 3000);




참조 :
http://blog.naver.com/PostView.nhn?blogId=huewu&logNo=110120532880


Tuesday, April 29, 2014

Android Activity is not working when installed by installer and click open button~

This is a strange
it happend from android OS version 1 from now on.
i'don't know why google dosen't fix it

anyway

it has a solution below

when called onCreate() in FirstActivity

check

if(!isTaskRoot()){
  finish();
  return;
}

I tested many time it working well.

and i hope it has no side effect.



if you want to use localstorage in Android

this is sigificant to add some line when you make webview


getSettings().setDomStorageEnabled(true);
getSettings().setDatabaseEnabled(true);
if(Build.VERSION.SDK_INT < 19){ // Build.VERSION_CODES.KITKAT = 19
getSettings().setDatabasePath("/data/data/" + getContext().getPackageName() + "/databases/");
}

Thursday, April 24, 2014

There are way to sync cookie in webview

in Webview Activity

when : onCreate
->  CookieSyncManager.createInstance(this);

when : onResum
-> CookieSyncManager.getInstance().startSync();

when : onPasue
-> CookieSyncManager.getInstance().stopSync();

When : onDestory 
-> CookieManager.getInstance().removeSessionCookie();


in WebClient
when : onPageFinished
-> CookieSyncManager.getInstance().sync();

that is all when you make a webapp application with session 

Monday, April 14, 2014

Android Register Broadcast and using it

this is usually set onStart and onStop in activity

onStart you register Receiver

this.registerReceiver(lockBroadcastReceiver, new IntentFilter(BroadCastConstant.LOCK_BROAD_CAST));


onStop you unregister Receiver

this.unregisterReceiver(lockBroadcastReceiver);



and Receiver sample Class
this is just example

private BroadcastReceiver lockBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {

String  initial = intent.getStringExtra("initial");
String  url = intent.getStringExtra("url");

if(initial == null)return;
if(url == null)return;


callAdStatistic(url, initial);
}
};


when you call it you can add parameters

Intent intent = new Intent();
intent.setAction(BroadCastConstant.LOCK_BROAD_CAST);
intent.putExtra("initial", initial);
intent.putExtra("url", url);
sendBroadcast(intent);

Tuesday, February 25, 2014

Android Test Cases

there are several cases you can use


Some common Test cases:
TestCase – It is a JUnit test case. It can be extended to test utility classes that are not tied to the Android framework.
AndroidTestCase – It extends JUnit’s TestCase. It doesn’t need to launch an activity to run it. It can be used when user wants to access Resources that depend on Activity Context.
ActivityInstrumentationTestCase2<T extends android.app.Activity> – It provides UI and functional testing for a single activity.
ActivityUnitTestCase<T extends android.app.Activity> – It gives the tested activity an isolated environment. The activity under test will be created with minimal connection to the system infrastructure.
ApplicationTestCase<T extends android.app.Application> – It provides

Monday, July 1, 2013

APK download internal storage and install

1. First Download
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            int fileLength = connection.getContentLength();
     
            File mkDir = mActivity.getDir("assets", Activity.MODE_WORLD_READABLE | Activity.MODE_WORLD_WRITEABLE);
            String path = mkDir.getAbsolutePath();
            Log.d("need", "ApkDownload Location : " + path);
           
         checkMemory(fileLength);  

            // download the file
            input = new BufferedInputStream(url.openStream());
            output = mActivity.openFileOutput(APK_FILE_NAME,
              Activity.MODE_WORLD_READABLE | Activity.MODE_WORLD_WRITEABLE);
//            output = new FileOutputStream(mActivity.getFilesDir().getAbsoluteFile() + File.separator + APK_FILE_NAME);
//            output = new FileOutputStream(SDCardRoot + File.separator + APK_FILE_NAME);
            Log.d("need", "ApkDownload Location : " + path);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                progressPercent =(int) (total * 100 / fileLength);
                publishProgress();
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();


2. Second Install
File fileLocation = new File(mActivity.getFilesDir(), ApkFileDownloadTask.APK_FILE_NAME);
         
Log.d("need", "apkFile isFile" + fileLocation.isFile());
Log.d("need", "apkFile getName" + fileLocation.getName());
Log.d("need", "apkFile getAbsolutePath" + fileLocation.getAbsolutePath());
Log.d("need", "apkFile getAbsolutePath" + fileLocation.length());
         
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileLocation), "application/vnd.android.package-archive");

startActivity(intent);

Sunday, May 26, 2013

Friday, April 19, 2013

HttpClient setCookies from Webview in android

this is real

I seached a bunch of time but there are nothing to work

this is a solution

if you are interested in Huybrid Webview

doing this


URI uri = new URI("http://www.xxx.xxxx/files/test.jsp");

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);

String cookies = CookieManager.getInstance().getCookie(
"http://203.233.82.229/files/test.jsp");
Log.i("cookie", "cookie " + cookies);

httpPost.setHeader("Cookie", cookies);
HttpResponse response = httpclient.execute(httpPost);

Tuesday, March 12, 2013

match against in mysql


CREATE TABLE `articles` (
  `id` int(11) NOT NULL DEFAULT '0',
  `title` varchar(65) DEFAULT NULL,
  `topic` varchar(25) NOT NULL DEFAULT '',
  `author` varchar(25) NOT NULL DEFAULT '',
  `ondate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `body` text NOT NULL,
  KEY `index_id` (`id`),
  FULLTEXT KEY `title` (`title`,`body`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8$$



select id,title FROM articles WHERE
    MATCH(title) AGAINST ('+cvs' IN BOOLEAN MODE) limit 1000;

what you have to consier is depending on DB Engine