2012년 11월 8일 목요일

센차터치2 + 폰갭 코믹뷰어 소스공개 4탄

이제 폰갭쪽 소스로 넘어옵니다... 폰갭소스는 1탄에서 폰 폴더 중 하단에 있는 부분입니다.
제가 안드로이드만 알고 아이폰은 잘 모르는 관계로 이부분은 안드로이드 기준으로 설명드립니다...

먼저 Activity를 살펴보겠습니다. 안드로이드가 이해되지 않으시면
센차터치2 + 폰갭의 안드로이드 설치 부분을 살펴보세요...

ImageViewrActivity.java 파일입니다.. --------------------------------
조금 복잡해진 부분이 있죠... Configuration.ORIENTATION_LANDSCAPE 와 PORTRAIT 부분이 있는데
왜이리 복잡해 졌을까요?????
만화를 볼때 가로모드까지 하단광고를 넣으면 .. 만화를 보기가 힘들어집니다...
그래서 세로모드만 애드몹 광고를 보여주도록 바꿔보았습니다... 몇시간 고민했네요...TT..

package com.lbo.imageviewer;
import com.google.ads.*;
import android.app.Activity;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import org.apache.cordova.*;
public class ImageViewerActivity extends DroidGap implements SensorEventListener {
/** Called when the activity is first created. */

AdView adView = null;
LinearLayout layout = null;
boolean isInit = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
adView = new AdView(this, AdSize.BANNER, "a1504841c828d31");
layout = super.root;
layout.addView( adView );
adView.setVisibility(View.VISIBLE);
adView.loadAd(new AdRequest());
if(getResources().getConfiguration().orientation ==Configuration.ORIENTATION_LANDSCAPE)
{
try
{
layout.removeView( adView );
}
catch(Exception e){}
}
isInit = true;
}

@Override
public void onConfigurationChanged(Configuration newConfig){
android.util.Log.i("", "--------------------come in");
super.onConfigurationChanged(newConfig);
if(isInit == true)
{
if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
try
{
layout.removeView(adView);
}
catch(Exception exTemp){}
layout.addView(adView);
}
else if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
try
{
layout.removeView(adView);
}
catch(Exception ex){}
}
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent arg0) {
}
}

다음은 폰갭 플러그인 부분입니다.... 플러그인의 사용도 책의 내용에 포함됩니다...
어디어디를 바꾸는지는 잘 읽어보시면 나옵니다....

ExecFile.java 파일입니다... --------------------------------------------
크게 2가지 기능이 있습니다.
처음 폴더리스트를 열때.. 폴더를 검색해서 이미지를 조회해 오는 기능이 있습니다...
두번째로는 파일목록의 파일 리스트를 조회해 오는 기능이 있습니다..
물론 이 기능이 폰갭의 파일API에도 있습니다.... 한데.. 속도가 좀 느려서요...App에서 바로 처리하도록
폰갭 플러그인으로 개발했습니다...

package com.phonegap.plugin.execfile;
import java.io.File;
import java.util.List;
import java.util.Vector;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;

public class ExecFile extends Plugin {
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.trim().equals("exec")) {
result = this.exec(args.getString(0), args.optJSONObject(1).getString("package"));
}
else if (action.equals("getPackageList")) {
result = this.getPackageList(args.getString(0));
}
else if (action.equals("searchFile")) {
result = this.searchFile(args.getString(0), args.getString(1)); //.optJSONObject(1).getString("rootPath"));
}
else if (action.equals("searchDir")) {
result = this.searchDir(args.getString(0), args.getString(1)); //.optJSONObject(1).getString("rootPath"));
}
return new PluginResult(status, result);
} catch (Exception e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
public String exec(String inputFile, String inputPackage) {
try
{
String mimeType = "";
int S = inputFile.lastIndexOf(".");
String extName = inputFile.substring(S);
extName = extName.toLowerCase();
if( extName.equals(".gif") ||
extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp"))
{
mimeType = "image/*";
}
else if( extName.equals(".mp3")||
extName.equals(".ogg") ||
extName.equals(".3ga"))
{
mimeType = "audio/*";
}
else if( extName.equals(".mp4") ||
extName.equals(".kmv") ||
extName.equals(".avi"))
{
mimeType = "video/*";
}
else if( extName.equals(".html") ||
extName.equals(".xml") ||
extName.equals(".css") ||
extName.equals(".htm"))
{
mimeType = "text/html";
}
else if( extName.equals(".text") ||
extName.equals(".txt") ||
extName.equals(".doc") ||
extName.equals(".info"))
{
mimeType = "text/*";
}
else if( extName.equals(".pdf"))
{
mimeType = "application/pdf";
}
else if( extName.equals(".rtf"))
{
mimeType = "application/rtf";
}
else if( extName.equals(".xls") ||
extName.equals(".xlsx"))
{
mimeType = "application/vnd.ms-wxcel";
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addCategory(intent.CATEGORY_DEFAULT);
intent.setDataAndType(Uri.parse(inputFile), mimeType);
this.ctx.startActivity(intent);
}
catch(Exception ex)
{
Toast.makeText(this.ctx.getContext() , "Can't Open File", 5000).show();
}
return "";
}
public String getPackageList(String inputFile) {
Log.i("", "getPackageList:" + inputFile);
PackageManager pm = this.ctx.getContext().getPackageManager();
List<ApplicationInfo> packs = pm.getInstalledApplications(
PackageManager.GET_META_DATA);
String result = "[";
int count_i = 0;
for(int i=0; i<packs.size(); i++ ){
ApplicationInfo app= (ApplicationInfo)packs.get(i);
if(app.packageName.contains("com.android") || app.packageName.contains("com.google"))
{
if(count_i != 0)
result = result + ",";
result = result + "{'l': '" + app.loadLabel(pm).toString() + "'," +
"'p':'" + app.packageName + "'}";
count_i++;
}
}
result = result + "]";
result = result.replace("\n","");
return result;
}

public String searchFile(String inputValue, String pathName)
{
pathName = pathName.replace("file://", "");
String result = "";
FileEntity fileList = new FileEntity();
try
{
fileList.getFileList(pathName, inputValue);

File[] files = fileList.getFiles();
int size = files.length;

for(int i=0; i< size-1; i++)
{
String fileName = files[i].getAbsolutePath();
for(int j=i+1; j < size; j++)
{
if(fileName.compareTo(files[j].getName()) < 0)
{
File tempFile = files[i];
files[i] = files[j];
files[j] = tempFile;
}
}
}
for(int i=0; i<size;i++)
{
if(i != 0)
{
result = result + ",";
}
String fileName = files[i].getAbsolutePath();
String fileNameSmpl = files[i].getName();
String filePath = fileName.substring(0, fileName.lastIndexOf("/"));
fileName = fileName.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
filePath = filePath.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
result = result + "{'id':'" + i + "', 'subject':'" + fileNameSmpl + "', 'content':'" + filePath + "', 'img':'" + fileName + "'}";
}
}
catch(Exception exTemp){
Log.i("", "exTemp:" + exTemp.toString());
}
return "[" + result + "]";
}
public String searchDir(String inputValue, String pathName)
{
pathName = pathName.replace("file://", "");
String result = "";
FileEntity fileList = new FileEntity();
try
{
fileList.getFolderList(pathName, inputValue);
File[] files = fileList.getFiles();
int size = files.length;
int divRowSize = 0;
String[][] pathDiv = new String[size][20];
String[][] fileDiv = new String[size][20];
int[] divSize = new int[size];
for(int i=0; i<size;i++)
{
String fileName = files[i].getAbsolutePath();
String filePath = fileName.substring(0, fileName.lastIndexOf("/"));
fileName = fileName.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
filePath = filePath.replace("'","^^1").replace("&","^^3").replace("\n","^^2").replace("'","^^4");
Log.i("", "filePath:" + filePath);
Log.i("", "fileName:" + fileName);
boolean isExist = false;



for(int j=0; j< divRowSize; j++)
{
if(pathDiv[j][0].equals(filePath))
{
pathDiv [j][divSize[j]] = filePath;
fileDiv [j][divSize[j]] = fileName;
divSize[j]++;
isExist = true;
break;
}
}
if(isExist== false)
{
pathDiv [divRowSize][0] = filePath;
fileDiv [divRowSize][0] = fileName;
divSize[divRowSize]++;
divRowSize++;
}
}
result = "";
for(int i=0; i< divRowSize;i++)
{
if(i != 0)
{
result = result + ",";
}
result = result + "{ 'path': '" + pathDiv[i][0] + "',";
for(int j=0;j<divSize[i];j++)
{
result = result + "'img" + j + "':'" + fileDiv[i][j] + "',";
}
for (int j=divSize[i]; j <5; j++)
{
result = result + "'img" + j + "':'./img/blank.png',";
}
result= result + " 'isFile':'N'}";
}
}
catch(Exception exTemp){
Log.i("", "exTemp:" + exTemp.toString());
}
return "[" + result + "]";
}
class FileEntity
{
Vector vecFileList;
FileEntity()
{
vecFileList = new Vector();
}
public File[] getFiles()
throws Exception
{
File[] files = new File[vecFileList.size()];
for(int i=0; i<vecFileList.size(); i++)
{
files[i] = (File)vecFileList.get(i);
}
return files;
}
public File[] getFileList(String path, String searchText)
throws Exception
{
File dir = new File(path);
File[] files = dir.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
if(file.isFile())
{
String fileName = file.getName();
int temp_i = fileName.lastIndexOf(".");
if(temp_i > 0)
{
String extName = fileName.substring(temp_i);
if( extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp") ||
extName.equals(".gif"))
{
vecFileList.add(file.getAbsoluteFile());
}
}
}
}
return files;
}
public File[] getFolderList(String path, String searchText)
throws Exception
{
File dir = new File(path);

Log.i("", "" + path);
File[] files = dir.listFiles();

int tempCount = 0;
for(int i=0; i<files.length; i++)
{
File file = files[i];
if(file.isFile())
{
String fileName = file.getName();
int temp_i = fileName.lastIndexOf(".");
if(temp_i > 0)
{
String extName = fileName.substring(temp_i);
if( extName.equals(".jpg") ||
extName.equals(".jpeg") ||
extName.equals(".png") ||
extName.equals(".tif") ||
extName.equals(".tiff") ||
extName.equals(".bmp") ||
extName.equals(".gif"))
{
if(tempCount < 3)
{
vecFileList.add(file.getAbsoluteFile());
}
tempCount++;
}
}
}
else if(file.isDirectory())
{
getFolderList(file.getCanonicalPath().toString(), searchText);
}
}
return files;
}
}
}


도움이 되셨나요.... 나름 도움도되고 책선전도 되고..해서요....
센차터치2 + 폰갭의 부록에 나오는 이미지(코믹)뷰어에 대한 설명이었습니다...
앞부분을 이해하셔야 처리하실수 있습니다...

부록에는 파일매니져도 있는데요... 파일목록에서 파일을 클릭하면 해당 파일을 복사하거나 삭제, 이동할수 있는 기능이외에
동영상을 클릭하면 동영상이 출력되고, 이미지를 클릭하면 이미지가 보이고. 음악을 클릭하면 음악이 보이고
pdf를 클릭하면 pdf가 보이도록 처리되는 기능을 만들어 보았습니다...한데 이소스는 MVC가 아니라 좀 지저분합니다.

아뭏든 이미지 뷰어를 MVC로 구성해서 올려보았습니다...
센차터치를 공부하는데 도움이 되셨으면 합니다....

참.... 한가지 갤럭시S3에서 올릴때 한가지 주의사항입니다... 그냥올리면 실행이 안돼죠...
index.html의 소스를 잘 살펴보세요.. 그리고 그대로 올리세요. 그럼 실행됩니다.

참고로 전 삼국지 만화를 이걸로 다 보았습니다.. 볼만 합니다....

그럼...도움이되셨길...

댓글 없음:

댓글 쓰기