【问题标题】:How to call android activities into phonegap html?如何将android活动调用到phonegap html中?
【发布时间】:2012-08-13 17:36:47
【问题描述】:

我最近开始研究 phonegap,我遇到了一个任务,我需要从 android mobile 浏览文件并显示所选文件的路径。我已经在phonegap中进行了很多搜索以实现这一目标,但我看到的所有示例都能够从手机图库中搜索和上传图片,但我想从手机中选择任何类型的文件。我听说我们可以将 android 本机代码调用到 phonegap html 中,所以我使用本机代码实现了我的功能,这里是我的 Activity 类:

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

private static final int REQUEST_PICK_FILE = 1;

private TextView mFilePathTextView;
private Button mStartActivityButton;
private File selectedFile;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
    mStartActivityButton = (Button)findViewById(R.id.start_file_picker_button);
    mStartActivityButton.setOnClickListener(this);      
}

public void onClick(View v) {
    switch(v.getId()) {
    case R.id.start_file_picker_button:
        Intent intent = new Intent(this, FilePickerActivity.class);
        startActivityForResult(intent, REQUEST_PICK_FILE);
        break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == RESULT_OK) {
        switch(requestCode) {
        case REQUEST_PICK_FILE:
            if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
                selectedFile = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
                mFilePathTextView.setText(selectedFile.getPath());  

            }
        }
    }
}

FilePickerActivity.java

public class FilePickerActivity extends ListActivity {

public final static String EXTRA_FILE_PATH = "file_path";
public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
private final static String DEFAULT_INITIAL_DIRECTORY = "/";

protected File mDirectory;
protected ArrayList<File> mFiles;
protected FilePickerListAdapter mAdapter;
protected boolean mShowHiddenFiles = false;
protected String[] acceptedFileExtensions;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View emptyView = inflator.inflate(R.layout.file_picker_empty_view, null);
    ((ViewGroup)getListView().getParent()).addView(emptyView);
    getListView().setEmptyView(emptyView);

    mDirectory = new File(DEFAULT_INITIAL_DIRECTORY);

    mFiles = new ArrayList<File>();

    mAdapter = new FilePickerListAdapter(this, mFiles);
    setListAdapter(mAdapter);

    acceptedFileExtensions = new String[] {};

    if(getIntent().hasExtra(EXTRA_FILE_PATH)) {
        mDirectory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH));
    }
    if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES)) {
        mShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
    }
    if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
        ArrayList<String> collection = getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
        acceptedFileExtensions = (String[]) collection.toArray(new String[collection.size()]);
    }
}

@Override
protected void onResume() {
    refreshFilesList();
    super.onResume();
}

protected void refreshFilesList() {
    mFiles.clear();

   ExtensionFilenameFilter filter = new ExtensionFilenameFilter(acceptedFileExtensions);

    File[] files = mDirectory.listFiles(filter);
    if(files != null && files.length > 0) {
        for(File f : files) {
            if(f.isHidden() && !mShowHiddenFiles) {
                continue;
            }

            mFiles.add(f);
        }

        Collections.sort(mFiles, new FileComparator());
    }
    mAdapter.notifyDataSetChanged();
}

@Override
public void onBackPressed() {
    if(mDirectory.getParentFile() != null) {
        mDirectory = mDirectory.getParentFile();
        refreshFilesList();
        return;
    }

    super.onBackPressed();
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    File newFile = (File)l.getItemAtPosition(position);

    if(newFile.isFile()) {
        Intent extra = new Intent();
        extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
        setResult(RESULT_OK, extra);
         finish();
    } else {
        mDirectory = newFile;
        refreshFilesList();
    }

    super.onListItemClick(l, v, position, id);
}

private class FilePickerListAdapter extends ArrayAdapter<File> {

    private List<File> mObjects;

    public FilePickerListAdapter(Context context, List<File> objects) {
        super(context, R.layout.file_picker_list_item, android.R.id.text1, objects);
        mObjects = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = null;

        if(convertView == null) { 
            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.file_picker_list_item, parent, false);
        } else {
            row = convertView;
        }

        File object = mObjects.get(position);

        ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
        TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
        textView.setSingleLine(true);

        textView.setText(object.getName());
        if(object.isFile()) {
            imageView.setImageResource(R.drawable.file);
        } else {
            imageView.setImageResource(R.drawable.folder);
        }

        return row;
    }

}

private class FileComparator implements Comparator<File> {
    public int compare(File f1, File f2) {
        if(f1 == f2) {
            return 0;
        }
        if(f1.isDirectory() && f2.isFile()) {
            return -1;
        }
        if(f1.isFile() && f2.isDirectory()) {
             return 1;
        }
        return f1.getName().compareToIgnoreCase(f2.getName());
    }
}

private class ExtensionFilenameFilter implements FilenameFilter {
    private String[] mExtensions;

    public ExtensionFilenameFilter(String[] extensions) {
        super();
        mExtensions = extensions;
    }

    public boolean accept(File dir, String filename) {
        if(new File(dir, filename).isDirectory()) {
            return true;
        }
        if(mExtensions != null && mExtensions.length > 0) {
            for(int i = 0; i < mExtensions.length; i++) {
                if(filename.endsWith(mExtensions[i])) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }
}

现在我想在 phonegap html 中使用这些活动。我从这些网站上看到了一些示例 site1 site2 site3 但无法了解如何在其中使用我的活动课程。谁能帮助我如何在phonegap中调用我的上述2个活动课程?我希望我的问题很清楚。

这是我的 xml:

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:gravity="top">
<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/start_file_picker_button"
    android:text="Browse" />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Selected file"
    android:textStyle="bold"
    android:textColor="#0f894a"
    android:textSize="24sp" />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/file_path_text_view"
    android:text="No file has been selected"
    android:textSize="28sp" />
</LinearLayout>

file_view.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"

android:padding="6dip">

<ImageView
    android:id="@+id/icon"

    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_marginRight="6dip"

    android:src="@drawable/ic_launcher" />

<LinearLayout
    android:orientation="vertical"

    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"

        android:gravity="center_vertical"
        android:text="My Application" />

    <TextView  
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" 

        android:singleLine="true"
        android:ellipsize="marquee"
        android:text="Simple application that shows how to use RelativeLayout" />

</LinearLayout>

file_picker_list_item.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal" >
<ImageView
  android:id="@+id/file_picker_image"
  android:layout_width="40dip"
  android:layout_height="40dip"
  android:layout_marginTop="5dip"
  android:layout_marginBottom="5dip"
  android:layout_marginLeft="5dip"
  android:src="@drawable/file"
  android:scaleType="centerCrop"/>
 <TextView
  android:id="@+id/file_picker_text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  android:layout_gravity="left|center_vertical"
  android:textSize="24sp"
  android:layout_marginLeft="10dip"
  android:singleLine="true"
  android:text="filename"/>
 </LinearLayout>

file_picker_empty_view.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:text="No files or directories"
     android:background="@android:drawable/toast_frame"
     android:textSize="24sp"
     android:gravity="center_vertical|center_horizontal"/>

【问题讨论】:

    标签: android cordova


    【解决方案1】:

    你需要创建一个类似的帮助类:

    public class HelperClass extends Plugin implements OnClickListener 
    
        protected static final String TAG = null;
        private DroidGap mGap;
        public HelperClass(DroidGap gap, WebView view)
        {
            mGap = gap;
        }   
           @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
        mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
        mStartActivityButton = (Button)findViewById(R.id.start_file_picker_button);
        mStartActivityButton.setOnClickListener(this);      
    }
    
        public void onClick(View v) {
        switch(v.getId()) {
        case R.id.start_file_picker_button:
            Intent intent = new Intent(this, FilePickerActivity.class);
            startActivityForResult(intent, REQUEST_PICK_FILE);
            break;
        }
    }   
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(resultCode == RESULT_OK) {
                switch(requestCode) {
                case REQUEST_PICK_FILE:
                    if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
                        selectedFile = new     File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
                        mFilePathTextView.setText(selectedFile.getPath());  
    
                }
            }
        }
    }
    
    @Override
    public PluginResult execute(String arg0, JSONArray arg1, String arg2) {
        // TODO Auto-generated method stub
        return null;
    }
    

    }

    那么你的主要活动需要是这样的:

            public class MainActivity extends DroidGap {
        /** Called when the activity is first created. */
    HelperClass cna;
        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        super.init();    
        cna = new HelperClass(this, appView);    
        appView.addJavascriptInterface(cna, "HelperClass");      
        super.loadUrl("file:///android_asset/www/index.html");
        }
    }
    

    【讨论】:

    • 你需要在 assets 文件夹中有 phoneGap.js 以及 index.html 和 style.css。只要记住在html文件中添加js和css文件的链接即可。
    • 能否请您发布您的 xml,因为这些是我似乎得到的唯一错误。
    • 好吧,问题是你的布局应该是 assets 文件夹中的网页。
    • 你应该使用 index.html 作为你的主要布局。您是否考虑过在没有 phoneGap 的情况下这样做?
    • 好的,所以请给我一个简短的解释,说明您正在尝试做什么,我们可以从那里开始,记住代码与本机代码不同,这就是 phonegap 的全部意义 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多