У меня есть эти коды:
UploadSong (этот код контроллера ввода:< /p>
Код: Выделить всё
package com.example.zeneshare.controller;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.example.zeneshare.R;
import com.example.zeneshare.Utils.FileUtils;
import com.example.zeneshare.adapter.AudioPickerContract;
import com.example.zeneshare.model.song;
import com.example.zeneshare.services.UploadService;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
public class UploadSong extends AppCompatActivity {
private FirebaseUser user;
private ActivityResultLauncher audioPickerLauncher;
private String filePath;
private TextView TVfilePathShow;
private EditText ETSongAuthor;
private EditText ETSongTitle;
private FirebaseFirestore songDB;
private CollectionReference songRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
user= FirebaseAuth.getInstance().getCurrentUser();
if (user != null && getIntent().getIntExtra("upload",1)==1){
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_upload_song);
audioPickerLauncher = registerForActivityResult(new AudioPickerContract(), this::onAudioFileSelected);
TVfilePathShow = findViewById(R.id.songURL);
ETSongAuthor = findViewById(R.id.songAuthor);
ETSongTitle = findViewById(R.id.songTitle);
songDB=FirebaseFirestore.getInstance();
songRef = songDB.collection("Songs");
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
else if(user != null){
finish();
Intent openList = new Intent(this, MainPageAfterLoggedIn.class);
startActivity(openList);
}
else {
finish();
Intent openLogin = new Intent(this, MainActivity.class);
startActivity(openLogin);
}
}
public void selectFile(View view) {
audioPickerLauncher.launch("audio/*");
}
@SuppressLint("ResourceAsColor")
private void onAudioFileSelected(Uri selectedAudioUri){
filePath = selectedAudioUri.getPath();
TVfilePathShow.setText(filePath);
TVfilePathShow.setTextColor(R.color.black);
}
@SuppressLint("ResourceAsColor")
public void upload(View view) {
if (filePath == null){
TVfilePathShow.setText("Adj meg egy fajlt!");
TVfilePathShow.setTextColor(R.color.red);
}
else {
Intent intent = new Intent(this, UploadService.class);
intent.putExtra("fileUri", filePath);
//TODO: Megformazni jora a fileformatumot.
String songAuthor = ETSongAuthor.getText().toString();
String songTitle = ETSongTitle.getText().toString();
String[] filePathParts = filePath.split("/");
songRef.add(new song(songTitle,songAuthor,filePathParts[filePathParts.length-1]+"audio", user.getEmail()))
.addOnSuccessListener(documentReference -> {
Log.i(UploadSong.class.getName(),"Letrehozva");
})
.addOnFailureListener(documentReference -> {
Log.e(UploadSong.class.getName(),"Error");
});
startService(intent);
finish();
Intent intent2 = new Intent(this, MainPageAfterLoggedIn.class);
startActivity(intent2);
}
}
}
Код: Выделить всё
package com.example.zeneshare.adapter;
import static android.app.Activity.RESULT_OK;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class AudioPickerContract extends ActivityResultContract {
@NonNull
@Override
public Intent createIntent(@NonNull Context context, String s) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(s);
return intent;
}
@Override
public Uri parseResult(int i, @Nullable Intent intent) {
if (intent == null || i != RESULT_OK) {
return null;
}
return intent.getData();
}
}
Код: Выделить всё
package com.example.zeneshare.services;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import com.example.zeneshare.R;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
public class UploadService extends Service {
private static final String TAG = "UploadService";
private StorageReference storageRef;
private static final String CHANNEL_ID = "UploadServiceChannel";
@Override
public void onCreate(){
super.onCreate();
storageRef = FirebaseStorage.getInstance().getReference();
}
@SuppressLint("ForegroundServiceType")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String fileUri = intent.getStringExtra("fileUri");
if (fileUri != null) {
String[] fileUriParts = fileUri.split(":");
Uri contentUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
ContentResolver cR = getApplicationContext().getContentResolver();
Uri realFileUri = Uri.withAppendedPath(contentUri,fileUriParts[1]);
startForeground(1,createNotification());
File file = new File(String.valueOf(realFileUri));
Log.i(TAG,String.valueOf(file.length()));
Log.i(TAG,realFileUri.toString());
uploadFile(realFileUri);
}
return START_NOT_STICKY;
}
private void uploadFile(Uri fileUri) {
StorageReference songsRef = storageRef.child("songs");
String[] fileUriParts = fileUri.toString().split("/");
StorageReference fileRef = songsRef.child(fileUriParts[fileUriParts.length-1]+".mp3");
Log.i(TAG,fileRef.toString());
ContentResolver cR = getApplicationContext().getContentResolver();
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType("audio/mpeg")
.build();
UploadTask uploadTask = fileRef.putFile(fileUri, metadata);
uploadTask.addOnProgressListener(taskSnapshot -> {
long bytesTransferred = taskSnapshot.getBytesTransferred();
long totalBytes = taskSnapshot.getTotalByteCount();
int progress = (int) ((100.0 * bytesTransferred) / totalBytes);
Log.i(TAG,""+progress);
updateProgressNotification(progress);
}).addOnSuccessListener(taskSnapshot -> {
Log.d(TAG, "Upload successful");
stopForeground(true);
stopSelf();
}).addOnFailureListener(exception -> {
Log.e(TAG, "Upload failed: " + exception.getMessage());
stopForeground(true);
stopSelf();
});
}
private Notification createNotification() {
createNotificationChannel();
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Uploading...")
.setContentText("Upload in progress")
.setSmallIcon(R.drawable.baseline_arrow_upward_24)
.build();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Upload Channel";
String description = "Channel for upload progress notification";
NotificationManager notificationManager = getSystemService(NotificationManager.class);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
}
}
private void updateProgressNotification(int progress) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Uploading...")
.setContentText(progress + "% completed")
.setProgress(100, progress, false)
.setSmallIcon(R.drawable.baseline_arrow_upward_24)
.build();
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.notify(1, notification);
}
private void cancelProgressNotification() {
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.cancel(1);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Размер файла в Firestore: 8,7 КБ, в то время как в эмуляторе : 5,06 МБ
Я пытался загрузить на физическое устройство, но результат тот же. Логарифм пишет следующее сообщение: Загрузка прошла успешно.
Я пытаюсь загрузить файл, но Firebase не получает его содержимое. Пожалуйста, постарайтесь мне помочь!
Подробнее здесь: https://stackoverflow.com/questions/783 ... o-firebase
Мобильная версия