티스토리 뷰

구글플레이에서 앱 버전 체크

Dexx 2016. 3. 16. 07:12

안드로이드 어플리케이션 업데이트 방법을 고민하던 중 구글플레이에서 정보를 가져와 업데이트를 유도하는 방법을 구현한 블로그를 찾았다.

 [참고] http://gun0912.tistory.com/8


자세하게 잘 설명되어 있지만 실제 구현해 보니 android.os.NetworkOnMainThreadException 이 나왔다.

이 에러는 네트워크 관련 처리를 메인 쓰레드에서 처리할 경우 발생하게 된다고 한다.

나 같은 초짜는 이런 부분이 어렵고 난감하다.

그래서 내가 위 참고 소스에서 추가로 구현한 부분을 정리해 보았다.


우선 HTML 파싱을 위해 Jsoup 라이브러리가 필요하다.

라이브러리는 http://jsoup.org/download에서 다운로드 받거나, 그레들에 다음과 같이 추가하면 된다.

1
2
3
dependencies {
    compile 'org.jsoup:jsoup:1.8.3'
}
cs


MarketVersionChecker.java

패키지명의 구글플레이 앱 소개 페이지에서 버전 정보를 가져와서 String으로 리턴한다.


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
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MarketVersionChecker {
    public static String getMarketVersion(String packageName) {
        
        Log.d("받은 값", packageName);
        
        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + packageName).get();
            Elements Version = document.select(".content");
            for (Element element : Version) {
                if (element.attr("itemprop").equals("softwareVersion")) {
                    return element.text().trim();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
 
    public static String getMarketVersionFast(String packageName) {
        
        String mData = "", mVer = null;
        try {
            URL mUrl = new URL("https://play.google.com/store/apps/details?id=" + packageName);
            HttpURLConnection mConnection = (HttpURLConnection) mUrl.openConnection();
            if (mConnection == null) {
                return null;
            }
 
            mConnection.setConnectTimeout(5000);
            mConnection.setUseCaches(false);
            mConnection.setDoOutput(true);
 
            if (mConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(mConnection.getInputStream()));
                while(true) {
                    String line = bufferedReader.readLine();
                    if (line == null)
                        break;
                    mData += line;
                }
                bufferedReader.close();
            }
            mConnection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
 
        String startToken = "softwareVersion\">";
        String endToken = "<";
        int index = mData.indexOf(startToken);
 
        if (index == -1) {
            mVer = null;
        } else {
            mVer = mData.substring(index + startToken.length(), index + startToken.length() + 100);
            mVer = mVer.substring(0, mVer.indexOf(endToken)).trim();
        }
        return mVer;
    }
}
cs


MainActivity.java

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
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.lang.ref.WeakReference;
 
public class MainActivity extends AppCompatActivity {
 
    String deviceVersion;
    String storeVersion;
 
    private BackgroundThread mBackgroundThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBackgroundThread = new BackgroundThread();
        mBackgroundThread.start();
    }
 
    public class BackgroundThread extends Thread {
        @Override
        public void run() {
 
            // 패키지 네임 전달
            String storeVersion = MarketVersionChecker.getMarketVersion(getPackageName());
 
            // 디바이스 버전 가져옴
            try {
                deviceVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            deviceVersionCheckHandler.sendMessage(deviceVersionCheckHandler.obtainMessage());
            // 핸들러로 메세지 전달
        }
    }
    
    private final DeviceVersionCheckHandler deviceVersionCheckHandler = new DeviceVersionCheckHandler(this);
    
    // 핸들러 객체 만들기
    private static class DeviceVersionCheckHandler extends Handler{
        private final WeakReference<MainActivity> mainActivityWeakReference;
        public DeviceVersionCheckHandler(MainActivity mainActivity) {
            mainActivityWeakReference = new WeakReference<MainActivity>(mainActivity);
        }
        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mainActivityWeakReference.get();
            if (activity != null) {
                activity.handleMessage(msg);
                // 핸들메세지로 결과값 전달
            }
        }
    }
 
    private void handleMessage(Message msg) {
        //핸들러에서 넘어온 값 체크
        if (storeVersion.compareTo(deviceVersion) > 0) {
            // 업데이트 필요
            
            AlertDialog.Builder alertDialogBuilder =
                new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_DeviceDefault_Light));
                alertDialogBuilder.setTitle("업데이트");alertDialogBuilder
                    .setMessage("새로운 버전이 있습니다.\n보다 나은 사용을 위해 업데이트 해 주세요.")
                    .setPositiveButton("업데이트 바로가기"new DialogInterface.OnClickListener() {
    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    // 구글플레이 업데이트 링크
                    }
            });
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.setCanceledOnTouchOutside(true);
            alertDialog.show();
 
        } else {
            // 업데이트 불필요
            
        }
    }
}
cs


'Android 개발 메모' 카테고리의 다른 글

Floating Labels 관련 잘 정리 내용  (0) 2016.03.17
Roboto 폰트 스타일 변경  (0) 2016.03.10
다이얼로그 띄우기 (AlertDialog)  (0) 2016.03.10
댓글