<android>如何创建一个从Web上获取文件的按钮</android>

时间:2013-02-12 15:10:17

标签: java android xml button

我想制作一个下载按钮,允许用户从网上下载或打开mp4文档。有可能成功吗?

文件:MP4

视频资源:http://wisdom.gotdns.com/application/android/res/test.mp4

视频分辨率:1280 * 720

*我应该在xml文件或java文件中添加什么内容?


这是我的按钮。

<Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    android:layout_marginTop="60dp"
    android:textColor="#ffffff" 
    android:background="#333"
    android:text="@string/tab2_watch" />

1 个答案:

答案 0 :(得分:0)

因为链接已经死了我无法测试这是否有效,但我很确定我做得很好。

MainActivity.java:

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String EXAMPLE_URL = "here goes your URL";

    private DownloadReceiver mDownloadReceiver;

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

        setContentView(R.layout.main);

        mDownloadReceiver = new DownloadReceiver();

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DownloadService.class);
                intent.putExtra(Constants.KEY_DOWNLOAD_URL, EXAMPLE_URL);

                startService(intent);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "starting download.. be patient", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

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

        LocalBroadcastManager.getInstance(this).registerReceiver(mDownloadReceiver, new IntentFilter(Constants.RECEIVER_NAME));
    }

    @Override
    protected void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(mDownloadReceiver);
    }

    private class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int mode = intent.getIntExtra(Constants.KEY_MODE, 0);
            final String message = intent.getStringExtra(Constants.KEY_MESSAGE);

            switch (mode) {
            case Constants.VALUE_MODE_ERROR:
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "an error occurred: " + message, Toast.LENGTH_LONG).show();
                    }
                });

                break;

            case Constants.VALUE_MODE_SUCCESSFUL:
                showVideoView(message);

                break;
            }
        }

        private void showVideoView(String filePath) {
            Intent intent = new Intent(MainActivity.this, VideoActivity.class);
            intent.putExtra(Constants.KEY_MESSAGE, filePath);

            startActivity(intent);
        }
    }
}

DownloadService.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.content.LocalBroadcastManager;

public class DownloadService extends IntentService {

    public DownloadService() {
        super("downloadService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String url = intent.getStringExtra(Constants.KEY_DOWNLOAD_URL);

        try {
            checkIfSdcardIsAvailableForStorage();
        }

        catch (SdcardNotAvailableException e) {
            e.printStackTrace();
            sendBroadcastIntent(Constants.VALUE_MODE_ERROR, e.getMessage());

            return;
        }

        try {
            File file = downloadFile(url);

            sendBroadcastIntent(Constants.VALUE_MODE_SUCCESSFUL, file.getAbsolutePath());
        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
            sendBroadcastIntent(Constants.VALUE_MODE_ERROR, "there was a problem with the downloading");
        }

        catch (IOException e) {
            e.printStackTrace();
            sendBroadcastIntent(Constants.VALUE_MODE_ERROR, "there was a problem reading the downloaded file");
        }
    }

    private File downloadFile(String url) throws ClientProtocolException, IOException {
        HttpGet httpGet = new HttpGet(url);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpGet);

        File path = Environment.getExternalStorageDirectory();
        File file = new File(path, "downloaded_file_" + System.currentTimeMillis());

        byte[] bs = IOUtils.toByteArray(response.getEntity().getContent());
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(bs);
        fileInputStream.close();

        return file;
    }

    private void checkIfSdcardIsAvailableForStorage() throws SdcardNotAvailableException {
        String state = Environment.getExternalStorageState();

        if (state.equals(Environment.MEDIA_REMOVED)) {
            throw new SdcardNotAvailableException("the sdcard is currently not mounted");
        }

        if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            throw new SdcardNotAvailableException("the sdcard is currently in read only mode.");
        }
    }

    private class SdcardNotAvailableException extends Exception {
        private static final long serialVersionUID = 1L;

        public SdcardNotAvailableException(String string) {
            super(string);
        }
    }

    private void sendBroadcastIntent(int mode, String message) {
        if (mode == 0) {
            throw new RuntimeException("mode may not be 0");
        }

        if (message == null) {
            throw new RuntimeException("message may not be null");
        }

        Intent intent = new Intent(Constants.RECEIVER_NAME);
        intent.putExtra(Constants.KEY_MODE, mode);
        intent.putExtra(Constants.KEY_MESSAGE, message);

        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
    }
}

Constants.java

public class Constants {
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_MODE = "mode";
    public static final int VALUE_MODE_SUCCESSFUL = 1;
    public static final int VALUE_MODE_ERROR = 2;

    public static final String RECEIVER_NAME = "DownloadService";
    public static final String KEY_DOWNLOAD_URL = "downloadUrl";

    private Constants() {
    }
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="download" />

</LinearLayout>

video.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your package"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".VideoActivity" />

        <service android:name=".DownloadService" />
    </application>

</manifest>

libs文件夹中的依赖项:commons-io-2.4.jar(link)。

请注意,我已省略了这些包,因此您需要将其添加到您的包中。正如我之前所说,你的电影链接已经死了所以它可能无效,你将不得不尝试其他一些视频。

这样做是因为它创建了一个服务来获取文件并将其保存到SD卡。当它被下载时,它将通知活动以使用VideoView开始活动,该活动将获取文件的路径并播放它。

我倾向于过度使用它,但我认为正确性&gt;速度。这样,您还将学习下载文件的正确方法。

关于依赖性的注释:有许多不好的方法可以使InputStream成为字节数组。依赖性是最好和最快的方式。

告诉我一些事情是否正确。祝你好运!