Why doesn't it let me choose settings? - java

There is a simple application that should download a file to the watch at the click of a button. The first problem is that it downloads it every other time!
enter image description here
Even if it downloaded it and I try to open it
enter image description here
I have a settings window pop up so that I can give permissions
but when I click on the settings button, my application returns to the original window.
Main activity.java
public class MainActivity extends Activity {
private Button download;
private ActivityMainBinding binding;
private static final String URL = "https://xmonitoring.ru/load/auto_load.php";
private static final String FILE_NAME = "wearOs.apk";
private static final int DOWNLOAD_FILE = 100;
private static final int INSTALL_APK = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
downloadApk(URL, FILE_NAME);
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE);
}
} else {
downloadApk(URL, FILE_NAME);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == DOWNLOAD_FILE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
binding.download.performClick();
}
}
}
private void downloadApk(String url, String file) {
String fileName = URLUtil.guessFileName(file, null, "application/vnd.android.package-archive");
String folder = Environment.getExternalStorageDirectory() + "/Download/";
File newFile = new File(folder, fileName);
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setDescription(fileName)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI)
.setDestinationUri(Uri.fromFile(newFile))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setVisibleInDownloadsUi(true)
.setTitle(file);
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
assert manager != null;
long downloadID = manager.enqueue(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

How to access programmatically wide angle camera in android studio?

Im quite new to Android and I'm looking to find a way how to access the wide angle camera. I know how to list all my cameras on a certain device and I know how to see which camera I'm opening. I need to know how to set my camera to open the wide angle one. Thanks in advance ! I also read everything in android developers but there is nothing mentioning about the wide angle camera. And this is how I'm opening/activating my camera.
public class CameraActivity extends AppCompatActivity {
private static final String TAG = "cam";
private String lastImageUri;
private ListenableFuture<ProcessCameraProvider> cameraProviderListenableFuture;
private ImageCapture imageCapture;
private PreviewView previewView;
private PermissionManager permissionManager;
private final String[] permissions = {Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
Button buttonCameraSelectToDeleteImage = (Button) findViewById(R.id.buttonDeleteImage);
Button button = (Button) findViewById(R.id.buttonMain);
previewView = findViewById(R.id.previewView);
permissionManager = PermissionManager.getInstance(CameraActivity.this);
cameraProviderListenableFuture = ProcessCameraProvider.getInstance(getApplicationContext());
cameraProviderListenableFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderListenableFuture.get();
startCameraX(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}, getExecutor());
Button buttonCameraSelectToMakeAndSavePhoto = (Button) findViewById(R.id.buttonCameraSelectToMakeAndSavePhoto);
buttonCameraSelectToMakeAndSavePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!permissionManager.checkPermissions(permissions)) {
permissionManager.askPermission(CameraActivity.this, permissions, 100);
} else {
capturePhoto();
}
}
});
buttonCameraSelectToDeleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommonPropertiesArray.arrayOfUriStrings.remove(lastImageUri);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CameraActivity.this, AddInternActivity.class);
startActivity(intent);
}
});
// Context context = CameraActivity.this;
// CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
// try {
// String[] cameraIds = manager.getCameraIdList();
// Log.d("cameraIds", Arrays.toString(cameraIds));
// } catch (CameraAccessException e) {
// e.printStackTrace();
// }
}
private Executor getExecutor() {
return ContextCompat.getMainExecutor(this);
}
private void startCameraX(ProcessCameraProvider cameraProvider) {
cameraProvider.unbindAll();
// Camera Selector use case
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
// Preview use case
Preview preview = new Preview.Builder().build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
// Image capture use case
imageCapture = new ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build();
cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageCapture);
}
private void capturePhoto() {
long timeStamp = System.currentTimeMillis();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, timeStamp);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
imageCapture.takePicture(
new ImageCapture.OutputFileOptions.Builder(
getContentResolver(),
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
).build(),
getExecutor(),
new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
if (CommonPropertiesArray.arrayOfUriStrings.size() < 3) {
fileUri = (outputFileResults.getSavedUri());
lastImageUri = String.valueOf(fileUri);
CommonPropertiesArray.arrayOfUriStrings.add(lastImageUri);
Toast.makeText(CameraActivity.this, "Photo has been save successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CameraActivity.this, "You can make max 3 picture", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
Toast.makeText(CameraActivity.this, "Error saving photo: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
permissionManager.handlePermissionResult(CameraActivity.this, 100, permissions,
grantResults);
}
}

WhatsApp Status Saver Greater than Android 10 permission not working it stucks at splash screen but less then Android 10 will working fine

public class Splash extends AppCompatActivity {
private static final String MANAGE_EXTERNAL_STORAGE_PERMISSION = "android:manage_external_storage";
private final Handler handler = new Handler();
private static final int REQUEST_PERMISSIONS = 1234;
private static final String[] PERMISSIONS = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_activity);
//To hide action Bar(Tool Bar)
getSupportActionBar().hide();
if (!arePermissionDenied()){
next();
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && arePermissionDenied()) {
// If Android 11 Request for Manage File Access Permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_PERMISSIONS);
return;
}
requestPermissions(PERMISSIONS, REQUEST_PERMISSIONS);
}
}
#Override
protected void onResume() {
super.onResume();
if (!arePermissionDenied()) {
next();
}
}
#RequiresApi(api = Build.VERSION_CODES.R)
boolean checkStorageApi30() {
AppOpsManager appOps = getApplicationContext().getSystemService(AppOpsManager.class);
int mode = appOps.unsafeCheckOpNoThrow(
MANAGE_EXTERNAL_STORAGE_PERMISSION,
getApplicationContext().getApplicationInfo().uid,
getApplicationContext().getPackageName()
);
return mode != AppOpsManager.MODE_ALLOWED;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onRequestPermissionsResult
(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS && grantResults.length > 0) {
if (arePermissionDenied()) {
// Clear Data of Application, So that it can request for permissions again
((ActivityManager) Objects.requireNonNull(this.getSystemService(ACTIVITY_SERVICE))).clearApplicationUserData();
recreate();
} else {
next();
}
}
}
private boolean arePermissionDenied() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return checkStorageApi30();
}
for (String permissions : PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(),
permissions) != PackageManager.PERMISSION_GRANTED) {
return true;
}
}
return false;
}
private void next() {
handler.postDelayed(() -> {
startActivity(new Intent(Splash.this, MainActivity.class));
finish();
}, 1000);
}
}

Screen recording app does not work on Android 10

I have an application for recording a screen, it does not work on android version 10. As I understand it, this is due to privacy changes in force in Android 10. Now for any application using MediaProjection api, must specify an attribute android:foregroundServiceType= in the service tag under the manifest, but my application uses MediaProjection in the fragment, not the service. Is it possible to make MediaProjection work from a fragment, or do I need to redo it?
Sorry for my bad english
Here is a mistake
Caused by java.lang.SecurityException
Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
com.example.screen_recording.screens.main_record.MainFragment.onActivityResult (MainFragment.java:321)
Here is the snippet code
public class MainFragment extends Fragment {
SharedPreferences p;
TimerViewModel model;
private static final int REQUEST_CODE = 1000;
private static final int REQUEST_PERMISSION = 1001;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
private boolean isRecord = false;
private boolean isPause = false;
private boolean isNightTheme = false;
private String videoUri = "";
private MediaProjectionManager mediaProjectionManager;
private MediaProjection mediaProjection;
private VirtualDisplay virtualDisplay;
private MediaProjectionCallBack mediaProjectionCallBack;
private MediaRecorder mediaRecorder;
private int mScreenDensity;
private static int DISPLAY_WIDTH;
private static int DISPLAY_HEIGHT;
static {
ORIENTATIONS.append(Surface.ROTATION_0, 90);
ORIENTATIONS.append(Surface.ROTATION_90, 0);
ORIENTATIONS.append(Surface.ROTATION_180, 270);
ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
//View
private CardView rootLayout;
private VideoView videoView;
private ToggleButton toggleButton;
private TextView textViewTimer;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
p = PreferenceManager.getDefaultSharedPreferences(getActivity());
isNightTheme = p.getBoolean("isNightTheme", false);
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
DISPLAY_WIDTH = metrics.widthPixels;
DISPLAY_HEIGHT = metrics.heightPixels;
mediaRecorder = new MediaRecorder();
mediaProjectionManager = (MediaProjectionManager) getActivity().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
// View
videoView = view.findViewById(R.id.videoView);
rootLayout = view.findViewById(R.id.cardView);
toggleButton = view.findViewById(R.id.toggleButton);
textViewTimer = view.findViewById(R.id.textViewTimer);
// ViewModal
model = new ViewModelProvider(getActivity()).get(TimerViewModel.class);
textViewTimer.setText(model.timeState);
if (isNightTheme) {
rootLayout.setBackgroundResource(R.color.colorBlack);
textViewTimer.setTextColor(Color.WHITE);
}
// Event
//Record Toggle Start and Stop
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
errorRecordAction();
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.RECORD_AUDIO)) {
errorRecordAction();
Snackbar.make(rootLayout, "Разрешения", Snackbar.LENGTH_INDEFINITE)
.setAction("Включить", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
}, REQUEST_PERMISSION);
}
}).show();
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
}, REQUEST_PERMISSION);
}
} else {
toggleScreenShare(toggleButton);
}
}
});
return view;
}
private void toggleScreenShare(View v) {
if (((ToggleButton) v).isChecked()) {
int quality = p.getInt("quality", 480);
boolean micro = p.getBoolean("micro", false);
int fps = p.getInt("FPS", 15);
initRecorder(quality, micro, fps);
recorderScreen();
isRecord = true;
p.edit().putBoolean("isRecord", isRecord).apply();
} else {
mediaRecorder.stop();
mediaRecorder.reset();
stopRecordScreen();
videoView.setVisibility(View.VISIBLE);
videoView.setVideoURI(Uri.parse(videoUri));
videoView.start();
isRecord = false;
p.edit().putBoolean("isRecord", isRecord).apply();
getActivity().stopService(new Intent(getContext(), TimerService.class));
}
}
private BroadcastReceiver uiUpdated = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textViewTimer.setText(intent.getStringExtra("countdown"));
model.timeState = intent.getStringExtra("countdown");
}
};
private void recorderScreen() {
if (mediaProjection == null) {
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
return;
}
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
}
private VirtualDisplay createVirtualDisplay() {
return mediaProjection.createVirtualDisplay("MainFragment", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder.getSurface(), null, null);
}
private void initRecorder(int QUALITY, boolean isMicro, int fps) {
try {
if (isMicro) {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
if (isMicro) {
mediaRecorder.setAudioSamplingRate(44100);
mediaRecorder.setAudioEncodingBitRate(16 * 44100);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
}
videoUri = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
+ new StringBuilder("/FreeRecord_").append(new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss")
.format(new Date())).append(".mp4").toString();
mediaRecorder.setOutputFile(videoUri);
mediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoEncodingBitRate(40000);
mediaRecorder.setCaptureRate(fps);
mediaRecorder.setVideoFrameRate(fps);
int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mediaRecorder.setOrientationHint(orientation);
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != REQUEST_CODE) {
Toast.makeText(getActivity(), "Unk error", Toast.LENGTH_SHORT).show();
errorRecordAction();
return;
}
if (resultCode != Activity.RESULT_OK) {
Log.i("Разрешения", "Я зашел");
Toast.makeText(getActivity(), "Доступ запрещен", Toast.LENGTH_SHORT).show();
errorRecordAction();
return;
}
mediaProjectionCallBack = new MediaProjectionCallBack();
if (data != null) {
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
mediaProjection.registerCallback(mediaProjectionCallBack, null);
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
} else {
Toast.makeText(getActivity(), "Не удалось запустить запись", Toast.LENGTH_SHORT).show();
Log.i("dataActivity", "data = null");
}
getActivity().startService(new Intent(getContext(), TimerService.class));
getActivity().registerReceiver(uiUpdated, new IntentFilter("COUNTDOWN_UPDATED"));
}
private class MediaProjectionCallBack extends MediaProjection.Callback {
#Override
public void onStop() {
if (toggleButton.isChecked()) {
errorRecordAction();
mediaRecorder.stop();
mediaRecorder.reset();
}
mediaProjection = null;
stopRecordScreen();
super.onStop();
}
}
private void stopRecordScreen() {
if (virtualDisplay == null) {
return;
}
virtualDisplay.release();
destroyMediaProject();
}
private void destroyMediaProject() {
if (mediaProjection != null) {
mediaProjection.unregisterCallback(mediaProjectionCallBack);
mediaProjection.stop();
mediaProjection = null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSION: {
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
toggleScreenShare(toggleButton);
} else {
errorRecordAction();
Snackbar.make(rootLayout, "Права доступа", Snackbar.LENGTH_INDEFINITE)
.setAction("Включить", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
}, REQUEST_PERMISSION);
}
}).show();
}
return;
}
}
}
private void errorRecordAction() {
getActivity().stopService(new Intent(getContext(), TimerService.class));
isRecord = false;
toggleButton.setChecked(false);
mediaRecorder.reset();
}
}
You should use a foreground service inside the fragment to capture the screen.
Find below links for how to use the foreground service to capture the screen.
How to take a Screenshot from a background-service class using MediaProjection API?

How can save call History in phone storage?like as a backup

I want to make a calls log backup and recovery Application.
I have done some initial work. like call the CallLog API and show in ListView. but now How can save in internal or external storage.after that we can recover this call history through theses backup file.
enter image description here enter code here
enter image description here
public class Backup_Activity extends AppCompatActivity {
private static final int READ_LOGS = 725;
private ListView logList;
private Runnable logsRunnable;
private String[] requiredPermissions = {Manifest.permission.READ_CALL_LOG, Manifest.permission.READ_CONTACTS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_backup);
logList = findViewById(R.id.listview_id);
logsRunnable = new Runnable() {
#Override
public void run() {
loadLogs();
}
};
// Checking for permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissionToExecute(requiredPermissions, READ_LOGS, logsRunnable);
} else {
logsRunnable.run();
}
}
// This is to be run only when READ_CONTACTS and READ_CALL_LOG permission are granted
private void loadLogs() {
LogsManager logsManager = new LogsManager(this);
List<LogObject> callLogs = logsManager.getLogs(LogsManager.ALL_CALLS);
LogsAdapter logsAdapter = new LogsAdapter(Backup_Activity.this, R.layout.log_layout, callLogs);
logList.setAdapter(logsAdapter);
}
// A method to check if a permission is granted then execute tasks depending on that particular permission
#TargetApi(Build.VERSION_CODES.M)
private void checkPermissionToExecute(String permissions[], int requestCode, Runnable runnable) {
boolean logs = ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED;
boolean contacts = ContextCompat.checkSelfPermission(this, permissions[1]) != PackageManager.PERMISSION_GRANTED;
if (logs || contacts) {
requestPermissions(permissions, requestCode);
} else {
// runnable.run();
}
}
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == READ_LOGS && permissions[0].equals(Manifest.permission.READ_CALL_LOG) && permissions[1].equals(Manifest.permission.READ_CONTACTS)) {
if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED && grantResults[1] == PermissionChecker.PERMISSION_GRANTED) {
logsRunnable.run();
} else {
new AlertDialog.Builder(Backup_Activity.this)
.setMessage("The app needs these permissions to work, Exit?")
.setTitle("Permission Denied")
.setCancelable(false)
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
checkPermissionToExecute(requiredPermissions, READ_LOGS, logsRunnable);
}
})
.setNegativeButton("Exit App", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).show();
}
}
}
public void backup(View view) {
LogsManager logsManager = new LogsManager(this);
List<LogObject> callLogs = logsManager.getLogs(LogsManager.ALL_CALLS);
LogsAdapter logsAdapter = new LogsAdapter(Backup_Activity.this, R.layout.log_layout, callLogs);
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + "/text/");
dir.mkdir();
File file = new File(dir, "back up calls log.VCF");
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(logsAdapter.toString().getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();}
}}
class LogsAdapter extends ArrayAdapter<LogObject> {
List<LogObject> logs;
Context context;
int resource;
public LogsAdapter(Context context, int resource, List<LogObject> callLogs) {
super(context, resource, callLogs);
this.logs = callLogs;
this.context = context;
this.resource = resource;
}
#Override
public Context getContext() {
return context;
}
#Override
public int getCount() {
return logs.size();
}
#Override
public LogObject getItem(int position) {
return logs.get(position);
}
#Override
#SuppressLint("ViewHolder")
#RequiresPermission(Manifest.permission.READ_CONTACTS)
public View getView(int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(getContext()).inflate(resource, parent, false);
TextView phone = (TextView) row.findViewById(R.id.number_id);
TextView name=row.findViewById(R.id.name_id);
TextView duration = (TextView) row.findViewById(R.id.call_duration);
TextView date = (TextView) row.findViewById(R.id.call_time);
// ImageView profileView=row.findViewById(R.id.profile_id);
ImageView imageView = (ImageView) row.findViewById(R.id.calls_image_id);
LogObject log = getItem(position);
Date date1 = new Date(log.getDate());
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.ERA_FIELD, DateFormat.SHORT);
name.setText(log.getContactName());
phone.setText(log.getNumber());
duration.setText(log.getCoolDuration());
date.setText(dateFormat.format(date1));
// profileView.setImageResource(log.getDuration());
switch (log.getType()) {
case LogsManager.INCOMING:
imageView.setImageResource(R.drawable.received);
break;
case LogsManager.OUTGOING:
imageView.setImageResource(R.drawable.sent);
break;
case LogsManager.MISSED:
imageView.setImageResource(R.drawable.missed);
break;
default:
imageView.setImageResource(R.drawable.cancelled);
break;
}
return row;
}
}

record audio and play it issue

I am trying to make simple app just for learning purpose thats record an audio clip then upload the file to the firebase and here is my code
public class MainActivity extends AppCompatActivity {
private StorageReference mStorage;
Button recordeButton ;
TextView recorderLable ;
private MediaRecorder recorder;
private String fileName = null ;
private static final String LOG_TAG = "AudioRecordTest";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private MediaPlayer player = null;
ProgressDialog progressDialog ;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
recordeButton = findViewById(R.id.recordeButton) ;
recorderLable = findViewById(R.id.recordeLable) ;
fileName = getExternalCacheDir().getAbsolutePath();
fileName += "/audiorecordtest.3gp";
ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
progressDialog = new ProgressDialog(this) ;
recordeButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
startRecording();
recorderLable.setText("recording started");
} else if (event.getAction() == MotionEvent.ACTION_UP){
stopRecording();
recorderLable.setText("recording stopped");
}
return false ;
}
});
}
private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(fileName);
try {
recorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
recorder.start();
}
private void stopRecording() {
recorder.stop();
recorder.release();
recorder = null;
uploadAudio();
}
private void uploadAudio() {
progressDialog.setMessage("UPLOADING ...");
progressDialog.show();
String uniqueID = UUID.randomUUID().toString() ;
final StorageReference filePath = mStorage.child("Audio").child(uniqueID + ".mp3") ;
Uri uri = Uri.fromFile(new File(fileName)) ;
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
recorderLable.setText("AUDIO UPLOADED \uD83D\uDE0A");
filePath.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
final Uri path = task.getResult();
Log.i("AUDIO_URI", path.toString());
}
}
}) ;
}
}) ;
}
}
the problem is I've uploaded the file successfully but when I try to play it in the firebase nothing happen and length of the file is 0:00 which means that there is a problem in recording process not in uploading

Categories

Resources