要实现Android启动下载而无需1DM的文件弹出窗口,可以使用Android内置的DownloadManager类。以下是一个代码示例:
首先,在AndroidManifest.xml文件中添加以下权限:
然后,在你的Activity中,添加以下代码来处理下载文件的请求:
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
private static final String DOWNLOAD_URL = "https://example.com/file.zip"; // 替换为你要下载的文件URL
private Button downloadButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadButton = findViewById(R.id.downloadButton);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkPermission()) {
startDownload();
} else {
requestPermission();
}
}
});
}
private boolean checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
return true;
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startDownload();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void startDownload() {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DOWNLOAD_URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.zip"); // 替换为你想要保存的文件名
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
if (downloadManager != null) {
downloadManager.enqueue(request);
}
}
}
以上代码中,通过检查WRITE_EXTERNAL_STORAGE权限是否已授权来决定是否启动下载。如果未授权,则会请求授权。一旦权限被授予,就会使用DownloadManager启动下载,下载完成后会显示通知。在startDownload()方法中,你可以根据需要设置下载文件的保存路径和文件名。
请注意,为了使上述代码正常工作,确保替换DOWNLOAD_URL为你要下载的文件的实际URL,并在布局文件中添加一个Button元素,其id为downloadButton。