Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java <;安卓>;如何创建从web获取文件的按钮_Java_Android_Xml_Button - Fatal编程技术网

Java <;安卓>;如何创建从web获取文件的按钮

Java <;安卓>;如何创建从web获取文件的按钮,java,android,xml,button,Java,Android,Xml,Button,我想制作一个下载按钮,允许用户从web下载或打开mp4文档。有可能吗 文件:MP4 视频资源: 视频分辨率:1280*720 *我应该在xml文件或java文件中添加什么 这是我的按钮 <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="bottom" an

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

文件: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" />

由于链接已断开,我无法测试此功能是否有效,但我确信我已将其全部修复

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>

)

请注意,我省略了这些包,因此您需要将其添加到您的包中。正如我之前所说的,你的电影链接已失效,因此可能无法正常工作,你必须尝试使用其他视频

这样做的目的是创建一个服务,该服务将获取一个文件并将其保存到SD卡。下载文件后,它将向活动发出信号,以视频视图启动活动,视频视图将获取文件路径并播放该文件

我有时会做得太过分,但我认为正确性>速度。通过这种方式,您还将学习下载文件的正确方法

关于依赖关系的注意事项:将InputStream设置为字节数组有很多不好的方法。依赖项以最好、最快的方式实现这一点


如果有什么不对劲,告诉我。祝你好运

是的。然而,这个问题有两个重要部分:按钮和下载。你和哪一个有麻烦?我看到了你的按钮,但我没有看到任何下载代码。你试过什么?我是Android的新手,我不知道如何用按钮编写下载文档的代码。或者当点击按钮时使用内置浏览器访问网站的代码。这里有一些错误,如main activity.java DownloadSrevice.java@kawingtamkw你读过我写的吗?转到此处(),下载commons-io-2.4.jar并将其放在项目的libs文件夹中。当您在java文件(MainActivity、DownloadServce)中看到错误时,按Ctrl+Shift+O“组织导入”,它将修复您的问题。您还可以尝试“清理”项目。