public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
Button facedetect;
GraphicOverlay graphicOverlay;
CameraView cameraView;
AlertDialog alertDialog;
Bitmap captureImage, saveImage;
Bitmap b1,b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facedetect = findViewById(R.id.detect_face_btn);
graphicOverlay = findViewById(R.id.graphic_overlay);
cameraView = findViewById(R.id.camera_view);
facedetect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.start();
cameraView.captureImage();
graphicOverlay.clear();
}
});
cameraView.addCameraKitListener(new CameraKitEventListenerAdapter() {
#Override
public void onEvent(CameraKitEvent event) {
super.onEvent(event);
}
#Override
public void onError(CameraKitError error) {
super.onError(error);
}
#Override
public void onImage(CameraKitImage image) {
super.onImage(image);
alertDialog.show();
b1 = image.getBitmap();
b1 = Bitmap.createScaledBitmap(b1, cameraView.getWidth(), cameraView.getHeight(), false);
cameraView.stop();
getImageFromLocal();`enter code here`
// if ( compareImages(b1,b2)==true) {
// Toast.makeText(getApplicationContext(),"True",Toast.LENGTH_SHORT).show();
// }
// Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_SHORT).show();
processFaceDetaection(b1);
}
#Override
public void onVideo(CameraKitVideo video) {
super.onVideo(video);
}
});
}
private void processFaceDetaection(Bitmap bitmap) {
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionFaceDetectorOptions firebaseVisionFaceDetectorOptions = new FirebaseVisionFaceDetectorOptions.Builder().build();
// High-accuracy landmark detection and face classification
FirebaseVisionFaceDetectorOptions landmarkdetectionfacedetection =
new FirebaseVisionFaceDetectorOptions.Builder()
.setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
.setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
.setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
.build();
// Real-time contour detection of multiple faces
FirebaseVisionFaceDetectorOptions contourdetectionfacedetection =
new FirebaseVisionFaceDetectorOptions.Builder()
.setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
.build();
FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(firebaseVisionFaceDetectorOptions);
// FirebaseVisionFaceDetector firebaseVisionFaceDetector = FirebaseVision.getInstance().getVisionFaceDetector(contourdetectionfacedetection);
firebaseVisionFaceDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace>>() {
#Override
public void onSuccess(List<FirebaseVisionFace> firebaseVisionFaces) {
getFaceResult(firebaseVisionFaces);
compareFaceFromLocal();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
alertDialog.dismiss();
Toast.makeText(MainActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void compareFaceFromLocal() {
if (compareImages(b1, b2) == true) {
Toast.makeText(getApplicationContext(), "True", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "False", Toast.LENGTH_SHORT).show();
}
private void getFaceResult(List<FirebaseVisionFace> firebaseVisionFaces) {
int counter = 0;
for (FirebaseVisionFace face : firebaseVisionFaces) {
Rect rect = face.getBoundingBox();
ReactOverlay reactOverlay = new ReactOverlay(graphicOverlay, rect);
graphicOverlay.add(reactOverlay);
counter = counter + 1;
}
Toast.makeText(MainActivity.this, "No. of faces detected : " + counter, Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
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);
}
/**
* Get the angle by which an image must be rotated given the device's current
* orientation.
*/
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int getRotationCompensation(String cameraId, Activity activity, Context context)
throws CameraAccessException {
// Get the device's current rotation relative to its "native" orientation.
// Then, from the ORIENTATIONS table, look up the angle the image must be
// rotated to compensate for the device's rotation.
int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int rotationCompensation = ORIENTATIONS.get(deviceRotation);
// On most devices, the sensor orientation is 90 degrees, but for some
// devices it is 270 degrees. For devices with a sensor orientation of
// 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
CameraManager cameraManager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
int sensorOrientation = cameraManager
.getCameraCharacteristics(cameraId)
.get(CameraCharacteristics.SENSOR_ORIENTATION);
rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360;
// Return the corresponding FirebaseVisionImageMetadata rotation value.
int result;
switch (rotationCompensation) {
case 0:
result = FirebaseVisionImageMetadata.ROTATION_0;
break;
case 90:
result = FirebaseVisionImageMetadata.ROTATION_90;
break;
case 180:
result = FirebaseVisionImageMetadata.ROTATION_180;
break;
case 270:
result = FirebaseVisionImageMetadata.ROTATION_270;
break;
default:
result = FirebaseVisionImageMetadata.ROTATION_0;
Log.e(TAG, "Bad rotation value: " + rotationCompensation);
}
return result;
}
#Override
protected void onPause() {
super.onPause();
cameraView.stop();
}
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
private void getImageFromLocal() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
/*Compare two images.
* #param bitmap1
* #param bitmap2
* #return true iff both images have the same dimensions and pixel values.*/
public static boolean compareImages(Bitmap bitmap1, Bitmap bitmap2) {
if (bitmap1.getWidth() != bitmap2.getWidth() ||
bitmap1.getHeight() != bitmap2.getHeight()) {
return false;
}
for (int y = 0; y < bitmap1.getHeight(); y++) {
for (int x = 0; x < bitmap1.getWidth(); x++) {
if (bitmap1.getPixel(x, y) != bitmap2.getPixel(x, y)) {
return false;
}
}
}
return true;
}
public static Uri imageURI;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 0) {
if (data != null) {
try {
b2 = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
System.exit(0);
Log.e("result", "BAD");
}
}
}
Related
// Camera activity code
public class CamActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
AspectRatioFragment.Listener {
public static boolean activityStatus;
private Handler handler = new Handler();
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "CamActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
private static final int SELECT_PICTURE = 1;
private static final int[] FLASH_OPTIONS = {
CameraView.FLASH_AUTO,
CameraView.FLASH_OFF,
CameraView.FLASH_ON,
};
private static final int[] FLASH_ICONS = {
R.drawable.ic_flash_auto,
R.drawable.ic_flash_off,
R.drawable.ic_flash_on,
};
private static final int[] FLASH_TITLES = {
R.string.flash_auto,
R.string.flash_off,
R.string.flash_on,
};
private int mCurrentFlash;
private CameraView mCameraView;
private Handler mBackgroundHandler;
private FloatingActionButton fab;
private ImageView open_gallery;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_picture:
if (mCameraView != null) {
try {
mCameraView.takePicture();
/*handler.postDelayed(() ->
mCameraView.takePicture(),
500);*/
}catch (Exception e){
Log.e(TAG,"mCameraView"+e.toString());
}
}
break;
case R.id.open_gallery:
openGallery();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle1 = new Bundle();
bundle1.putString(TAG, TAG);
bundle1.putString(TAG, TAG);
mFirebaseAnalytics.logEvent(TAG, bundle1);
setContentView(R.layout.activity_camera_renderer);
mCameraView = findViewById(R.id.camera);
open_gallery = findViewById(R.id.open_gallery);
if (open_gallery!=null)
open_gallery.setOnClickListener(mOnClickListener);
activityStatus = true;
if (mCameraView != null) {
mCameraView.addCallback(mCallback);
}
fab = findViewById(R.id.take_picture);
if (fab != null) {
fab.setOnClickListener(mOnClickListener);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
//toolbar.setTitle("Camera");
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeCamera();
}
});
//Listen for capture image and close camera
registerReceiver(syncCamReceiver, new IntentFilter("Camera"));
}
#Override
public void onBackPressed() {
closeCamera();
super.onBackPressed();
}
/**CLose camera**/
private void closeCamera(){
try{
unregisterReceiver(syncCamReceiver);
}
catch (Exception e){
Log.d(TAG,"Error while unregistering");
}
SN88Constant.getIk6Obj(getApplicationContext()).sendPhotoSwitch(false);
CamActivity.this.finish();
}
BroadcastReceiver syncCamReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equalsIgnoreCase("Camera")) {
//0 for open cam, 1 take picture 2 close camera
if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==1){
fab .performClick();
}
else if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==2){
CamActivity.this.finish();
}
}
}
};
#Override
protected void onResume() {
activityStatus = true;
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
if (mCameraView != null)
mCameraView.start();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ConfirmationDialogFragment
.newInstance(R.string.camera_permission_confirmation,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION,
R.string.camera_permission_not_granted)
.show(getSupportFragmentManager(), FRAGMENT_DIALOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}catch (Exception e){
Log.d(TAG,"Camera_onresume"+e.toString());
}
super.onResume();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
closeCamera();
activityStatus = false;
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.camera_permission_not_granted,
Toast.LENGTH_SHORT).show();
}
// No need to start camera here; it is handled by onResume
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aspect_ratio:
FragmentManager fragmentManager = getSupportFragmentManager();
if (mCameraView != null
&& fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) {
final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
final AspectRatio currentRatio = mCameraView.getAspectRatio();
AspectRatioFragment.newInstance(ratios, currentRatio)
.show(fragmentManager, FRAGMENT_DIALOG);
}
return true;
case R.id.switch_flash:
if (mCameraView != null) {
mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
item.setTitle(FLASH_TITLES[mCurrentFlash]);
item.setIcon(FLASH_ICONS[mCurrentFlash]);
mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
}
return true;
case R.id.switch_camera:
if (mCameraView != null) {
try {
int facing = mCameraView.getFacing();
mCameraView.setFacing(facing == CameraView.FACING_FRONT ?
CameraView.FACING_BACK : CameraView.FACING_FRONT);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAspectRatioSelected(#NonNull AspectRatio ratio) {
if (mCameraView != null) {
//Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show();
try {
mCameraView.setAspectRatio(ratio);
}catch (Exception e){
Log.d(TAG,"onAspectRatioSelected"+e.toString());
}
}
}
private Handler getBackgroundHandler() {
if (mBackgroundHandler == null) {
HandlerThread thread = new HandlerThread("background");
thread.start();
mBackgroundHandler = new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
private CameraView.Callback mCallback
= new CameraView.Callback() {
#Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "onCameraOpened");
}
#Override
public void onCameraClosed(CameraView cameraView) {
Log.d(TAG, "onCameraClosed");
}
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT)
.show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
String folderPath = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdir();
}
File file = new File(folderPath,"/Img"+System.currentTimeMillis()+ ".png");
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data);
os.close();
scanFile(file.getAbsolutePath());
} catch (IOException e) {
Log.w(TAG, "Cannot write to " + file, e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// Ignore
}
}
}
}
});
}
};
public static class ConfirmationDialogFragment extends DialogFragment {
private static final String ARG_MESSAGE = "message";
private static final String ARG_PERMISSIONS = "permissions";
private static final String ARG_REQUEST_CODE = "request_code";
private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";
public static ConfirmationDialogFragment newInstance(#StringRes int message,
String[] permissions, int requestCode, #StringRes int notGrantedMessage) {
ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_MESSAGE, message);
args.putStringArray(ARG_PERMISSIONS, permissions);
args.putInt(ARG_REQUEST_CODE, requestCode);
args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
return new AlertDialog.Builder(getActivity())
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissions = args.getStringArray(ARG_PERMISSIONS);
if (permissions == null) {
throw new IllegalArgumentException();
}
ActivityCompat.requestPermissions(getActivity(),
permissions, args.getInt(ARG_REQUEST_CODE));
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
args.getInt(ARG_NOT_GRANTED_MESSAGE),
Toast.LENGTH_SHORT).show();
}
})
.create();
}
}
//Scans the saved file so it appears in the gallery
private void scanFile(String path) {
MediaScannerConnection.scanFile(this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
/*
* open gallery for image preview
* */
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
// Getting error :
E/CamActivity: mCameraViewjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.camera2.CaptureRequest$Builder.set(android.hardware.camera2.CaptureRequest$Key, java.lang.Object)' on a null object reference
so, after a year or two i started this project again... by the time it was outdated it worked fine... but since android x came out i wanted to upgrade my application and got stuck on a error i find it funny...
quick brief, i have button that makes me online / offline.. on pressing the button the map should zoom at my curr. location and add a marker.. but here comes the error :
Logcat:
Process: com.app.mk.transport, PID: 22142
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.app.mk.transport.DriverHome$16$1$1.onComplete(DriverHome.java:1110)
at com.firebase.geofire.GeoFire$2.onComplete(GeoFire.java:178)
at com.google.firebase.database.core.Repo$6.run(com.google.firebase:firebase-database##19.2.0:404)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
DriverHome.java ( Not The whole code ):
private void setUpAutocomplete() {
AutocompleteSupportFragment autocompleteFragment = new AutocompleteSupportFragment();
// final AutocompleteSupportFragment autocompleteFragment;
// autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setCountry("MK");
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), getResources().getString(R.string.google_open_api));
}
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ADDRESS));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
if (location_switch.isChecked()) {
destination = place.getAddress();
destination = destination.replace(" ", "+");
if (destination.contains("+(FYROM)")) {
destination = destination.replace("+(FYROM)", "");
}
mMap.clear();
getDirection();
}
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(DriverHome.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
Log.i("MITKASIN", "An error occurred: " + status);
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.driver_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_trip_history) {
// Handle the camera action
} else if (id == R.id.nav_way_bill) {
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_update_Info) {
showDialogUpdateInfo();
} else if (id == R.id.nav_sign_out) {
signOut();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showDialogUpdateInfo() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this);
alertDialog.setTitle("Update Information");
alertDialog.setMessage("Please fill in the informations");
LayoutInflater inflater = this.getLayoutInflater();
View dialog_change_pwd = inflater.inflate(R.layout.layout_update_information, null);
final TextInputEditText edt_Name = dialog_change_pwd.findViewById(R.id.edtName);
final TextInputEditText edt_Phone = dialog_change_pwd.findViewById(R.id.edtPhone);
final ImageView image_upload = (ImageView) dialog_change_pwd.findViewById(R.id.image_upload);
image_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
alertDialog.setView(dialog_change_pwd);
alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog.Builder()
.setContext(DriverHome.this)
.setTheme(R.style.Orange)
.setMessage(R.string.waitingDialog_title)
.setCancelable(false)
.build();
waitingDialog.show();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
String name = edt_Name.getText().toString();
String phone = edt_Phone.getText().toString();
Map<String, Object> updateInfo = new HashMap<>();
if (!TextUtils.isEmpty(name))
updateInfo.put("name", name);
if (!TextUtils.isEmpty(phone))
updateInfo.put("phone", phone);
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(updateInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Information updated!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Information update Failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(DriverHome.this, "Uploaded !", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(final Uri uri) {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
Map<String, Object> avatarUpdate = new HashMap<>();
avatarUpdate.put("avatarUrl", uri.toString());
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(avatarUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Uploaded!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Upload error !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mDialog.setMessage("Upliaded " + progress + "%");
}
});
}
}
}
private void signOut() {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
else
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to logout?")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Paper.init(this);
AccountKit.logOut();
Intent intent = new Intent(DriverHome.this, MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
private float getBearing(LatLng startPosition, LatLng endPosition) {
double lat = Math.abs(startPosition.latitude - endPosition.latitude);
double lng = Math.abs(startPosition.longitude - endPosition.longitude);
if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
private void updateFirebaseToken() {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tbl);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(account.getId())
.setValue(token);
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
private void getDirection() {
currentPosition = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());
String requestApi = null;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_reference=less_driving&" +
"origin=" + currentPosition.latitude + "," + currentPosition.longitude + "&" +
"destination=" + destination + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.i("MITKASIN", requestApi);
mServices.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
if (!polyLineList.isEmpty()) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 1);
mMap.animateCamera(mCameraUpdate);
// mMap.getUiSettings().setAllGesturesEnabled(true);
}
polylineOptiuons = new PolylineOptions();
polylineOptiuons.color(Color.GRAY);
polylineOptiuons.width(5);
polylineOptiuons.startCap(new SquareCap());
polylineOptiuons.endCap(new SquareCap());
polylineOptiuons.jointType(JointType.ROUND);
polylineOptiuons.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptiuons);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(7);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
if (!polyLineList.isEmpty()) {
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
}
//Animation
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
handler = new Handler();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 2000);
// mMap.getUiSettings().setScrollGesturesEnabled(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(DriverHome.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
// mMap.getUiSettings().setScrollGesturesEnabled(true);
}
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PEMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
buildLocationCallback();
buildLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PEMISSION_REQUEST_CODE);
} else {
buildLocationRequest();
buildLocationCallback();
if (location_switch.isChecked())
displayLocation();
}
}
private void buildLocationCallback() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Common.mLastLocation = location;
}
displayLocation();
}
};
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null) {
if (location_switch.isChecked()) {
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
//Update to Firebase
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
geoFire.setLocation(account.getId(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (mCurrent != null) {
mCurrent.remove();
}
mCurrent = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Your Location"));
// Move camera to this position when set to online!
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14.5f));
// Draw animation rotate marker
// rotateMarker(mCurrent, 360, mMap);
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
} else {
Log.d("ERROR", "Cannot get your location");
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
if (ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
excuse me for the nasty code tho :D
and sorry if its a dumb question but idk what im missing here ...
You need to call your displayLocation and getDirection methods only after the map has been initialized (i.e. mMap = googleMap). Check out related Null Pointer Exception and getMapAsync Error
E.g.:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
displayLocation();
getDirection();
}
Hope this helps!
I have 3 menu buttons (add_image,save_meme and share_meme) on my action bar, which are declared in Mainactivity.java. The buttons are responsible for calling the corresponding methods in another fragment. The connection is established with LocalBroadcastManager.
public class MainActivity extends AppCompatActivity{
Intent saveIntent, shareIntent, addImageIntent;
LocalBroadcastManager localBroadcastManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
addImageIntent = new Intent("ADD_ACTION");
saveIntent = new Intent("SAVE_ACTION");
shareIntent = new Intent("SHARE_ACTION");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
default:
return super.onOptionsItemSelected(item);
}
}
}
As mentioned above, the corresponding methods are in the TopImageFragment.java class. The add_image button calls the method that allows the user to upload an image to the ImageView from the device:
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
The save_meme button calls the method that saves the bitmap to the device:
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
The share_meme button calls the method that allows the user to share the meme on a variety of social media apps and email clients:
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
But what's happening now is that whenever I select whichever of the 3 menu buttons, all 3 methods get called. This is my full fragment:
public class TopImageFragment extends Fragment {
ImageView imageView;
TextView topTextView, bottomTextView;
RelativeLayout topImageRelativeLayout;
public static final int PICK_IMAGE = 1;
Uri imageUri;
int counter = 0;
String timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.CANADA).format(new Date());
float textSize, x, imageViewArea, canvasArea;
double val;
MemeViewModel memeViewModel;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_image, container, false);
imageView = view.findViewById(R.id.meme_image_view);
topTextView = view.findViewById(R.id.top_text_view);
bottomTextView = view.findViewById(R.id.bottom_text_view);
topImageRelativeLayout = view.findViewById(R.id.top_image_relative_layout);
if (savedInstanceState != null) {
imageUri = savedInstanceState.getParcelable("imageUri");
imageView.setImageURI(imageUri);
}
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("imageUri", imageUri);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
memeViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(MemeViewModel.class);
memeViewModel.getTopText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
topTextView.setText(charSequence);
}
});
memeViewModel.getBottomText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
bottomTextView.setText(charSequence);
}
});
}
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
public Bitmap getBitmap(ImageView img) {
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
return bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap screenshotMeme() {
Bitmap image = Bitmap.createBitmap(topImageRelativeLayout.getWidth(), topImageRelativeLayout.getHeight(), Bitmap.Config.RGB_565);
topImageRelativeLayout.draw(new Canvas(image));
return image.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap drawMeme(Bitmap mutableBitmap) {
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
topText = topText.toUpperCase();
bottomText = bottomText.toUpperCase();
Canvas canvas = new Canvas(mutableBitmap);
TextPaint topFillPaint = new TextPaint();
TextPaint bottomFillPaint = new TextPaint();
TextPaint topStrokePaint = new TextPaint();
TextPaint bottomStrokePaint = new TextPaint();
Typeface typeface = getResources().getFont(R.font.impact);
textSize = topTextView.getTextSize();
imageViewArea = (imageView.getWidth()) * (imageView.getHeight());
canvasArea = (canvas.getWidth()) * (canvas.getHeight());
val = textSize * sqrt(canvasArea / imageViewArea);
x = (float) val;
topFillPaint.setColor(Color.WHITE);
topFillPaint.setTextSize(x);
topFillPaint.setTypeface(typeface);
topFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
topStrokePaint.setStyle(Paint.Style.STROKE);
topStrokePaint.setStrokeWidth(4);
topStrokePaint.setTextSize(x);
topStrokePaint.setColor(Color.BLACK);
topStrokePaint.setTypeface(typeface);
bottomFillPaint.setColor(Color.WHITE);
bottomFillPaint.setTextSize(x);
bottomFillPaint.setTypeface(typeface);
bottomFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
bottomStrokePaint.setStyle(Paint.Style.STROKE);
bottomStrokePaint.setStrokeWidth(4);
bottomStrokePaint.setColor(Color.BLACK);
bottomStrokePaint.setTextSize(x);
bottomStrokePaint.setTypeface(typeface);
StaticLayout topFillLayout = new StaticLayout(topText, topFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout topStrokeLayout = new StaticLayout(topText, topStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomFillLayout = new StaticLayout(bottomText, bottomFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomStrokeLayout = new StaticLayout(bottomText, bottomStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
topFillLayout.draw(canvas);
topStrokeLayout.draw(canvas);
canvas.translate(0, canvas.getHeight() - bottomFillLayout.getHeight());
bottomFillLayout.draw(canvas);
bottomStrokeLayout.draw(canvas);
return mutableBitmap;
}
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = Objects.requireNonNull(data).getData();
imageView.setImageURI(imageUri);
memeViewModel.setSharedId(imageUri.getLastPathSegment());
}
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(addListener, new IntentFilter("ADD_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(saveListener, new IntentFilter("SAVE_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(shareListener, new IntentFilter("SHARE_ACTION"));
}
private BroadcastReceiver addListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
selectedImage();
}
};
private BroadcastReceiver saveListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
saveMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
saveMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
private BroadcastReceiver shareListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
shareMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
shareMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(addListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(saveListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(shareListener);
}
}
Problem: Because in switch-case block, you do not return or put a break statement, then whenever a menu item is clicked, it will executes all statements in the switch-case.
Solution: Put a return true on each case to indicate you want consume the event when a menu item is clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
return true;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
return true;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
or using a break statement on each case, then returning true at the end of method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
break;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
break;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
I'm trying to figure out how I would get the data in a Firebase database assigned to a particular user but that is proving very tricky for me.
So, for now, I would like to be able to attach the current signed-in/authenticated user's name/ID to any file that I save from my app but I don't know how to go about it.
I tried adding the following lines to my Camera Photo activity but it didn't do anything:
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
and then adding to the code where it assigns the file name (as such):
file = new File(Environment.getExternalStorageDirectory() + "/" + UUID.randomUUID().toString()
+ FirebaseAuth.getInstance().getCurrentUser() + ".jpg");
But, as I say, it doesn't do anything and just keeps the file name in the same format without any user ID associated with it.
Below is the full class for taking and saving a photo (without my added attempts):
public class CameraPhotoActivity extends AppCompatActivity {
private Button btnCapture;
private TextureView textureView;
// to check the state orientation of the output image
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
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);
}
private String cameraId;
private CameraDevice cameraDevice;
private CameraCaptureSession cameraCaptureSessions;
private CaptureRequest.Builder captureRequestBuilder;
private Size imageDimension;
private ImageReader imageReader;
// save to file
private File file;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private boolean mFlashSupported;
private Handler mBackgroundHandler;
private HandlerThread mBackgroundThread;
CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice camera) {
cameraDevice = camera;
createCameraPreview();
}
#Override
public void onDisconnected(#NonNull CameraDevice cameraDevice) {
cameraDevice.close();
}
#Override
public void onError(#NonNull CameraDevice cameraDevice, int i) {
cameraDevice.close();
cameraDevice = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_photo);
textureView = (TextureView) findViewById(R.id.textureView);
assert textureView != null;
textureView.setSurfaceTextureListener(textureListener);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
takePicture();
}
});
}
private void takePicture() {
if (cameraDevice == null)
return;
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
if (characteristics != null)
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
.getOutputSizes(ImageFormat.JPEG);
// capture the image with custom size
int width = 640;
int height = 480;
if (jpegSizes != null && jpegSizes.length > 0) {
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
final ImageReader reader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
// check the orientation on the device
int rotation = getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
file = new File(Environment.getExternalStorageDirectory() + "/" + UUID.randomUUID().toString()
+ ".jpg");
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
{
if (image != null)
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
} finally {
if (outputStream != null)
outputStream.close();
}
MediaScannerConnection.scanFile(CameraPhotoActivity.this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("External Storage", "Scanned" + path + ":");
Log.i("External Storage", "-> uri=" + uri);
}
});
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(CameraPhotoActivity.this, "Saved " + file, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
try {
cameraCaptureSession.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if (cameraDevice == null)
return;
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(CameraPhotoActivity.this, "Changed", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void updatePreview() {
if (cameraDevice == null)
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// check realtime permission if run higher than API 23
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
TextureView.SurfaceTextureListener textureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
openCamera();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You can't use the camera without permission", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if (textureView.isAvailable())
openCamera();
else
textureView.setSurfaceTextureListener(textureListener);
}
#Override
protected void onPause() {
stopBackgroundThread();
super.onPause();
}
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
}
Also, here is my login authentication class:
public class MainLoginActivity extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private Button mLoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private boolean isUserClickedBackButton = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_login);
mAuth = FirebaseAuth.getInstance();
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mLoginBtn = (Button) findViewById(R.id.loginBtn);
// connection to user authentication on firebase (database)
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(MainLoginActivity.this, MainActivity.class));
}
}
};
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSiginIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
// code for exiting from app by using back button on login page
public void onBackPressed() {
//moveTaskToBack(true);
if (!isUserClickedBackButton){
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
isUserClickedBackButton = true;
} else {
System.exit(0); // exits right out of app
super.onBackPressed();
}
}
// for login
private void startSiginIn() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
Toast.makeText(MainLoginActivity.this, "Please input email and password", Toast.LENGTH_LONG).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
Toast.makeText(MainLoginActivity.this, "Sign in problem. Please check email" +
" and password", Toast.LENGTH_LONG).show();
}
});
}
}
}
Again, any help and advice greatly appreciated.
Thanks
If you want to add the user name in the name of your file, you need to change this line of code:
file = new File(Environment.getExternalStorageDirectory()
+ "/" + UUID.randomUUID().toString()
+ FirebaseAuth.getInstance().getCurrentUser() + ".jpg");
with
file = new File(Environment.getExternalStorageDirectory()
+ "/" + UUID.randomUUID().toString()
+ FirebaseAuth.getInstance().getCurrentUser().getDisplayName() + ".jpg");
See, I have added a call to .getDisplayName() method.
I am working on mediaplayer app, but i have problem with onDestroy methods, i need to continue with playing music when i minimalize the app. But when i do it stops playing and throws errors or when i comment it, it is playing in background but problem is that it doesnt stop even when i kill the app, i can controll it just with my notification controller, but when i destroy controller by swiping, it is playing and i have music in background without music player.
public class MainActivity extends AppCompatActivity {
private MediaPlayerService player;
private boolean serviceBound = false;
private ArrayList<Audio> audioList;
private RWAdapter rwa;
private RecyclerView rv;
public static final String Broadcast_PLAY_NEW_AUDIO = "com.example.rsabo.mp3player.PlayNewAudio";
public static final String Broadcast_PAUSE_AUDIO= "com.example.rsabo.mp3player.PauseAudio";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
loadAudio();
initRW();
}
private void initRW(){
if (audioList.size()>0) {
rv = (RecyclerView) findViewById(R.id.myRecyclerView);
rv.setLayoutManager(new LinearLayoutManager(this));
;
rwa = new RWAdapter(audioList, getApplicationContext());
rv.setAdapter(rwa);
rv.addOnItemTouchListener(new MyTouchListener(this, new onItemClickListener() {
#Override
public void onClick(View view, int index) {
playAudio(index);
}
}));
}
}
//ulozi sa instancia
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("ServiceState", serviceBound);
}
//obnovi sa instancia tam kde bola naposledy ulozena
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
serviceBound = savedInstanceState.getBoolean("ServiceState");
}
//znici instanciu
#Override
protected void onDestroy() {
super.onDestroy();
// if(serviceBound){
// unbindService(serviceConnection);
// player.stopSelf();
// }
}
//viaze tuto triedu s prehravacom, nastavi hodnotu serviceBound na true ked sa vytvori spojenie
private ServiceConnection serviceConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
Toast.makeText(MainActivity.this, "Service bound", Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
//Metoda pozrie ci je sluzba aktivna,
//ak nie je, do uloziska hodi arraylist s pesnickami, a spusti sluzbu
//ak je vlozi do uloziska novy audioIndex a posle spravu ze ma spustit pesnicku
private void playAudio(int audioIndex){
if(!serviceBound){
Ulozisko ulozisko = new Ulozisko(getApplicationContext());
ulozisko.storeAudio(audioList);
ulozisko.storeAudioIndex(audioIndex);
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
Ulozisko ulozisko = new Ulozisko(getApplicationContext());
ulozisko.storeAudioIndex(audioIndex);
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
private void pauseAudio(){
Intent broadcastIntent = new Intent(Broadcast_PAUSE_AUDIO);
sendBroadcast(broadcastIntent);
}
//nacita pesnicky z mobilu
private void loadAudio() {
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);
if(cursor != null && cursor.getCount() > 0) {
audioList = new ArrayList<>();
while (cursor.moveToNext()){
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
audioList.add(new Audio(data, title, album, artist));
}
}
cursor.close();
}
}
MediaPlayerService
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
private static final int NOTIFICATION_ID = 101;
private MediaSessionManager mediaSessionManager;
private MediaSessionCompat mediaSession;
private MediaControllerCompat.TransportControls transportControls;
private MediaPlayer mediaPlayer;
private String mediaFile;
private int resumePosition;
private AudioManager audioManager;
private boolean hovor = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private ArrayList<Audio> audioList;
private int audioIndex = -1;
private Audio activeAudio;
private final IBinder iBinder = new LocalBinder();
private PlayStatus status;
public static final String ACTION_PLAY = "com.example.rsabo.mp3player.ACTION_PLAY";
public static final String ACTION_PAUSE = "com.example.rsabo.mp3player.ACTION_PAUSE";
public static final String ACTION_PREVIOUS = "com.example.rsabo.mp3player.ACTION_PREVIOUS";
public static final String ACTION_NEXT = "com.example.rsabo.mp3player.ACTION_NEXT";
public static final String ACTION_STOP = "com.example.rsabo.mp3player.ACTION_STOP";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
//pri vytvoreni zavola metody callStateListener(),registerJeNahlasReciever(), registerPlayNewAudio()
#Override
public void onCreate() {
super.onCreate();
callStateListener();
registerJeNahlasReciever();
registerPlayNewAudio();
}
//podla priority zvuku v systeme zvysi zvuk, ukonci, zastavi alebo stisi mediaPlayer
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
if (mediaPlayer == null) initMediaPlayer();
else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
//metoda na ziskanie AudioFocusu/priority hrania zvuku
private boolean requestAudioFocus() {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
//metoda ktora odstrani audioFocus
private boolean removeAudioFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager.abandonAudioFocus(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
#Override
public void onCompletion(MediaPlayer mp) {
skipToNext();
buildNotification(PlayStatus.PLAYING);
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.d("Media Player error", "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK" + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d("Media Player error", "MEDIA_ERROR_SERVER_DIED" + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d("Media Player error", "MEDIA_ERROR_UNKNOWN" + extra);
break;
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
class LocalBinder extends Binder {
MediaPlayerService getService() {
return MediaPlayerService.this;
}
}
//inicializacia mediaPlayeru, ak sa nenastavi cesta vyhodi chybu a zastavi sa
private void initMediaPlayer() {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// nastavi cestu k hudbe
mediaPlayer.setDataSource(activeAudio.getData());
} catch (IOException e) {
e.printStackTrace();
stopSelf();
}
mediaPlayer.prepareAsync();
}
//nastavenie funkcie tlacidla play
private void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
//nastavenie funkcie tlacidla stop
private void stopMedia() {
if (mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
//nastavenie funkcie tlacidla pause
private void pauseMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
resumePosition = mediaPlayer.getCurrentPosition();
}
}
//nastavenie funkcie tlacidla resume
private void resumeMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(resumePosition);
mediaPlayer.start();
}
}
//inicializuje prhravac, ak neziska audiofocus alebo cestu k hudbe zastavi sa
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Ulozisko ulozisko = new Ulozisko(getApplicationContext());
audioList = ulozisko.loadAudio();
audioIndex = ulozisko.loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
} catch (NullPointerException e) {
stopSelf();
}
if (!requestAudioFocus()) {
stopSelf();
}
if (mediaSessionManager == null) {
try {
initMediaSession();
initMediaPlayer();
} catch (RemoteException e) {
e.printStackTrace();
stopSelf();
}
buildNotification(PlayStatus.PLAYING);
}
handleIncomingActions(intent);
return super.onStartCommand(intent, flags, startId);
}
//metode prida zrusenie audiofocusu a nastavi prehravac na null, vypne phoneStateListener, odregistruje recievre, zmaze notifikaciu a vycisti playlist
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
stopMedia();
mediaPlayer.release();
}
removeAudioFocus();
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
removeNotification();
unregisterReceiver(jeNahlasReciever);
unregisterReceiver(playNewAudio);
new Ulozisko(getApplicationContext()).clearCacheAudioPlaylist();
}
//ked sa vyberu sluchadla tak sa hranie zastavi
private BroadcastReceiver jeNahlasReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
pauseMedia();
buildNotification(PlayStatus.PAUSED);
}
};
private void registerJeNahlasReciever() {
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(jeNahlasReciever, intentFilter);
}
//metoda ktora zisiti v akom stave je hovor, a ked telefon zvoni alebo prebieha hovor, zastavi prehravanie
private void callStateListener() {
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
hovor = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (mediaPlayer != null) {
if (hovor) {
hovor = false;
resumeMedia();
}
}
break;
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
//ked prepnem pesnicku tak sa pomocou tejto metody resetne prehravac a prepne na dalsiu pesnicku podla indexu ktory dostala v sprave
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// if(status == PlayStatus.PAUSED) {
audioIndex = new Ulozisko(getApplicationContext()).loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
updateInfo();
buildNotification(PlayStatus.PLAYING);
// } else if (status == PlayStatus.PLAYING){
// pauseMedia();
// updateInfo();
// buildNotification(PlayStatus.PAUSED);
// }
}
};
private void registerPlayNewAudio() {
IntentFilter filter = new IntentFilter(MainActivity.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(playNewAudio, filter);
}
//skontroluje ci mediaSessionManager existuje
//vytvori mediaSession a da mu controller
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return;
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
mediaSession = new MediaSessionCompat(getApplicationContext(), "Prehravac");
transportControls = mediaSession.getController().getTransportControls();
mediaSession.setActive(true);
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
updateInfo();
mediaSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
buildNotification(PlayStatus.PLAYING);
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
buildNotification(PlayStatus.PAUSED);
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
skipToNext();
updateInfo();
buildNotification(PlayStatus.PLAYING);
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
skipToPrevious();
updateInfo();
buildNotification(PlayStatus.PLAYING);
}
#Override
public void onStop() {
super.onStop();
removeNotification();
stopSelf();
}
#Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
}
});
}
//updatne aktualne info o pesnicke
private void updateInfo() {
Bitmap albumArt = BitmapFactory.decodeResource(getResources(), R.drawable.image);
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
//.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt)
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, activeAudio.getArtist())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, activeAudio.getAlbum())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getTitle())
.build());
}
//metoda ktora prepne pesnicku na dalsiu, ak je pesnicka posledna tak ju nastavi na prvu v zozname
private void skipToNext() {
if (audioIndex == audioList.size() - 1) {
audioIndex = 0;
activeAudio = audioList.get(audioIndex);
} else {
activeAudio = audioList.get(++audioIndex);
}
new Ulozisko(getApplicationContext()).storeAudioIndex(audioIndex);
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
}
//metoda ktora prepne pesnicku dozadu, ak je na zaciatku zoznamu tak ju nastavi na poslednu
private void skipToPrevious() {
if (audioIndex == 0) {
audioIndex = audioList.size() - 1;
activeAudio = audioList.get(audioIndex);
} else {
activeAudio = audioList.get(--audioIndex);
}
new Ulozisko(getApplicationContext()).storeAudioIndex(audioIndex);
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
}
//metoda ktora spravi v notifikacnom panely prehravac a vzdy ked sa vola tato metoda tak sa v notifikacii updatne info o pesnicke
private void buildNotification(PlayStatus playStatus) {
int notificationAction = android.R.drawable.ic_media_pause;
PendingIntent playAleboPause = null;
if (playStatus == PlayStatus.PLAYING) {
notificationAction = android.R.drawable.ic_media_pause;
playAleboPause = playbackAction(1);
status = PlayStatus.PLAYING;
} else if (playStatus == PlayStatus.PAUSED) {
notificationAction = android.R.drawable.ic_media_play;
playAleboPause = playbackAction(0);
status = PlayStatus.PAUSED;
}
Bitmap albumArt = BitmapFactory.decodeResource(getResources(), R.drawable.image);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setShowWhen(false)
.setStyle(new NotificationCompat.MediaStyle()
.setMediaSession(mediaSession.getSessionToken())
.setShowActionsInCompactView(0, 1, 2))
.setColor(getResources().getColor(R.color.colorPrimary))
//.setLargeIcon(activeAudio.)
.setSmallIcon(android.R.drawable.stat_sys_headset)
.setContentText(activeAudio.getArtist())
.setContentTitle(activeAudio.getTitle())
.setSubText(activeAudio.getAlbum())
.addAction(android.R.drawable.ic_media_previous, "previous", playbackAction(3))
.addAction(notificationAction, "pause", playAleboPause)
.addAction(ic_media_next, "next", playbackAction(2));
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
}
//zmaze notifikaciu
private void removeNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
// nastavenie akcie na tlacidla v notifikacii
private PendingIntent playbackAction(int cisloAkcie) {
Intent akcia = new Intent(this, MediaPlayerService.class);
switch (cisloAkcie) {
case 0:
akcia.setAction(ACTION_PLAY);
return PendingIntent.getService(this, cisloAkcie, akcia, 0);
case 1:
akcia.setAction(ACTION_PAUSE);
return PendingIntent.getService(this, cisloAkcie, akcia, 0);
case 2:
akcia.setAction(ACTION_NEXT);
return PendingIntent.getService(this, cisloAkcie, akcia, 0);
case 3:
akcia.setAction(ACTION_PREVIOUS);
return PendingIntent.getService(this, cisloAkcie, akcia, 0);
default:
break;
}
return null;
}
//metoda zisti ktora akcia je aktualna a zavola metodu cez transportControls
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) return;
String akcia = playbackAction.getAction();
if (akcia.equalsIgnoreCase(ACTION_PLAY)) {
transportControls.play();
} else if (akcia.equalsIgnoreCase(ACTION_PAUSE)) {
transportControls.pause();
} else if (akcia.equalsIgnoreCase(ACTION_NEXT)) {
transportControls.skipToNext();
} else if (akcia.equalsIgnoreCase(ACTION_PREVIOUS)) {
transportControls.skipToPrevious();
} else if (akcia.equalsIgnoreCase(ACTION_STOP)) {
transportControls.stop();
}
}
}
Try this to startForeground()
Notification.Builder mBuilder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_icon)
.setContentTitle(getString(R.string.title))
.setContentText("");
Intent resultIntent = new Intent(this, ResultIntent.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ParentStack.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mId = 1489;
startForeground(mId, mBuilder.build());