Background location service is not working in oppo and MI phones - android

In my android application,location service is implemented as background service.I have tested it with different phones(like samsung,micromax,Moto,lenovo,nexus) it works fine with all.But when i run in Oppo (colorOS) and MI (MIUI OS),my service is get stopped after some time interval.I have finished MainActivity with MainActivity.this.finish().

put following code on your activity above oncreate() method:
private FusedLocationProviderClient mFusedLocationClient;
EasyPermissionsLocation.PermissionCallbacks permissionCallbacks = new EasyPermissionsLocation.PermissionCallbacks() {
#Override
public void onPermissionsGranted(int requestCode, List perms) {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
SettingsClient client = LocationServices.getSettingsClient(SurveyActivity.this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(SurveyActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(SurveyActivity.this);
if (ActivityCompat.checkSelfPermission(SurveyActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(SurveyActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(SurveyActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
((SurveyApp)getApplication()).getUser().getCurrentSurvey().setLat(""+location.getLatitude());
((SurveyApp)getApplication()).getUser().getCurrentSurvey().setLng(""+location.getLongitude());
Toast.makeText(SurveyActivity.this, "Location Captured", Toast.LENGTH_SHORT).show();
}
}
});
}
});
task.addOnFailureListener(SurveyActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(SurveyActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
}
}
}
});
}
#Override
public void onPermissionsDenied(int requestCode, List perms, final boolean isAutoDenied) {
if (isAutoDenied) {
showDialog(getString(R.string.permanently_deny_location));
}
}
#Override
public void onPermissionsPermanentlyDeclined(int requestCode, List perms) {
showDialog(getString(R.string.permanently_deny_location));
}
};
call above code from oncreate method():-
EasyPermissionsLocation.requestPermissions(this, permissionCallbacks, getString(R.string.location_message), 100, Manifest.permission_group.LOCATION);
create this class:
public class EasyPermissionsLocation {
private static final String TAG = "EasyPermissions";
private static long timeWhenRequestingStart;
private static Object object;
private static AlertDialog dialog;
private static PermissionCallbacks callbacks;
private static HashMap<String, String[]> permissionGroups;
private static boolean shouldShowRationale = false;
public static boolean hasPermissions(Context context, String... perms) {
// Always return true for SDK < M, let the system deal with the permissions
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Log.w(TAG, "hasPermissions: API version < M, returning true by default");
return true;
}
for (String perm : perms) {
boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) ==
PackageManager.PERMISSION_GRANTED);
if (!hasPerm) {
return false;
}
}
return true;
}
public static void requestPermissions(final Object object, PermissionCallbacks callback, String rationale,
final int requestCode, final String... perms) {
requestPermissions(object, callback, rationale,
android.R.string.ok,
android.R.string.cancel,
requestCode, perms);
}
public static void requestPermissions(final Object obj, final PermissionCallbacks callback, String rationale,
#StringRes int positiveButton,
#StringRes int negativeButton,
final int requestCode, final String... permission) {
callbacks = callback;
object = obj;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// only for lower of M
callbacks.onPermissionsGranted(requestCode, new ArrayList<String>(Arrays.asList(permission)));
return;
}
checkCallingObjectSuitability(object);
final String[] perms = getActualPermissions(object,
permission);
if (perms.length <= 0) {
callbacks.onPermissionsGranted(requestCode, new ArrayList<String>(Arrays.asList(permission)));
return;
}
shouldShowRationale = false;
for (String perm : perms) {
shouldShowRationale = shouldShowRationale || shouldShowRequestPermissionRationale(object, perm);
}
if (shouldShowRationale) {
if (!TextUtils.isEmpty(rationale)) {
if (dialog == null) {
dialog = new AlertDialog.Builder(getActivity(object))
.setMessage(rationale)
.setCancelable(false)
.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog1, int which) {
executePermissionsRequest(object, perms, requestCode);
dialog.dismiss();
}
})
.create();
} else {
dialog.setMessage(rationale);
}
dialog.show();
} else {
executePermissionsRequest(object, perms, requestCode);
}
} else {
timeWhenRequestingStart = System.currentTimeMillis();
executePermissionsRequest(object, perms, requestCode);
}
}
private static String[] getActualPermissions(Object object, String[] permission) {
initPermissionGroups();
ArrayList<String> permissionList = new ArrayList<String>();
for (String indiPerm : permission) {
if (permissionGroups.containsKey(indiPerm)) {
String[] arr = permissionGroups.get(indiPerm);
for (String s : arr) {
if (!EasyPermissionsLocation.hasPermissions(getActivity(object), s)) {
permissionList.add(s);
}
}
} else {
if (!EasyPermissionsLocation.hasPermissions(getActivity(object), indiPerm)) {
permissionList.add(indiPerm);
}
}
}
Set<String> set = new LinkedHashSet<String>(permissionList);
return set.toArray(new String[set.size()]);
}
private static void initPermissionGroups() {
if (permissionGroups == null) {
permissionGroups = new HashMap<String, String[]>();
permissionGroups.put(Manifest.permission_group.CALENDAR, new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR});
permissionGroups.put(Manifest.permission_group.CAMERA, new String[]{Manifest.permission.CAMERA});
permissionGroups.put(Manifest.permission_group.CONTACTS, new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.GET_ACCOUNTS});
permissionGroups.put(Manifest.permission_group.LOCATION, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
permissionGroups.put(Manifest.permission_group.MICROPHONE, new String[]{Manifest.permission.RECORD_AUDIO});
permissionGroups.put(Manifest.permission_group.PHONE, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG, Manifest.permission.ADD_VOICEMAIL, Manifest.permission.USE_SIP, Manifest.permission.PROCESS_OUTGOING_CALLS});
permissionGroups.put(Manifest.permission_group.SENSORS, new String[]{Manifest.permission.BODY_SENSORS});
permissionGroups.put(Manifest.permission_group.SMS, new String[]{Manifest.permission.SEND_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_WAP_PUSH, Manifest.permission.RECEIVE_MMS});
permissionGroups.put(Manifest.permission_group.STORAGE, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE});
}
}
public static void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
// checkCallingObjectSuitability(object);
// PermissionCallbacks callbacks = (PermissionCallbacks) object;
// Make a collection of granted and denied permissions from the request.
boolean showRationale = false;
ArrayList<String> granted = new ArrayList<>();
ArrayList<String> denied = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String perm = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
granted.add(perm);
} else {
showRationale = shouldShowRequestPermissionRationale(object, perm);
if (!showRationale) {
timeWhenRequestingStart = System.currentTimeMillis() - 2;
}
denied.add(perm);
}
}
boolean isPermenantlyDisabled = false;
// Report granted permissions, if any.
if (!granted.isEmpty() && denied.isEmpty()) {
// Notify callbacks
callbacks.onPermissionsGranted(requestCode, granted);
}
//if 100% fail then check for whether timing
else if (granted.isEmpty() && !denied.isEmpty()) {
if (!shouldShowRationale && !showRationale) {
if (callbacks != null) {
callbacks.onPermissionsDenied(requestCode, denied, true);
}
} else {
long diff = System.currentTimeMillis() - timeWhenRequestingStart;
if (diff < 150) {
//means it is permenantly disabled
isPermenantlyDisabled = true;
if (callbacks != null) {
callbacks.onPermissionsPermanentlyDeclined(requestCode, denied);
}
}
Log.i("TAG", diff + "");
}
}
else if (!denied.isEmpty() && !isPermenantlyDisabled) {
callbacks.onPermissionsDenied(requestCode, denied, false);
}
}
#TargetApi(23)
private static boolean shouldShowRequestPermissionRationale(Object object, String perm) {
if (object instanceof Activity) {
return ActivityCompat.shouldShowRequestPermissionRationale((Activity) object, perm);
} else if (object instanceof Fragment) {
return ((Fragment) object).shouldShowRequestPermissionRationale(perm);
} else if (object instanceof android.app.Fragment) {
return ((android.app.Fragment) object).shouldShowRequestPermissionRationale(perm);
} else {
return false;
}
}
#TargetApi(23)
private static void executePermissionsRequest(Object object, String[] perms, int requestCode) {
checkCallingObjectSuitability(object);
if (object instanceof Activity) {
ActivityCompat.requestPermissions((Activity) object, perms, requestCode);
} else if (object instanceof Fragment) {
((Fragment) object).requestPermissions(perms, requestCode);
} else if (object instanceof android.app.Fragment) {
((android.app.Fragment) object).requestPermissions(perms, requestCode);
}
}
#TargetApi(11)
private static Activity getActivity(Object object) {
if (object instanceof Activity) {
return ((Activity) object);
} else if (object instanceof Fragment) {
return ((Fragment) object).getActivity();
} else if (object instanceof android.app.Fragment) {
return ((android.app.Fragment) object).getActivity();
} else {
return null;
}
}
private static void checkCallingObjectSuitability(Object object) {
// Make sure Object is an Activity or Fragment
boolean isActivity = object instanceof Activity;
boolean isSupportFragment = object instanceof Fragment;
boolean isAppFragment = object instanceof android.app.Fragment;
boolean isMinSdkM = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
if (!(isSupportFragment || isActivity || (isAppFragment && isMinSdkM))) {
if (isAppFragment) {
throw new IllegalArgumentException(
"Target SDK needs to be greater than 23 if caller is android.app.Fragment");
} else {
throw new IllegalArgumentException("Caller must be an Activity or a Fragment.");
}
}
}
public interface PermissionCallbacks {
void onPermissionsGranted(int requestCode, List<String> perms);
void onPermissionsDenied(int requestCode, List<String> perms, boolean isAutoDenied);
void onPermissionsPermanentlyDeclined(int requestCode, List<String> perms);
}
}
add in manifest:-
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
add following in app gradle file:
implementation 'com.google.android.gms:play-services-location:11.8.0'

Related

Splashscreen with runtime permissions

I have a splash screen on launching my app. So when showing the splash screen run time permission should show. I got this code below from github. But runtime permissions are not showing. Splash screen works fine, but runtime permission is not working when add this code below. I have added permissions read sms, read external storage, access location. I have given all these permissions in the manifest file also.
public class SplashActivity extends AppCompatActivity {
String loginstatus;
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
/* Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(SplashScreen.this,HomeActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();*/
}
private void permissioncheck() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("READ");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("COURLOC");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("FINELOC");
if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
permissionsNeeded.add("SMS");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
// Pre-Marshmallow
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
// Pre-Marshmallow
}
return;
}else
{
// Toast.makeText(this,"Permission",Toast.LENGTH_LONG).show();
LaunchApp();
}
//insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
Boolean cond;
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
// return false;
cond = false;
}
// return true;
cond = true;
} else {
// Pre-Marshmallow
cond = true;
}
return cond;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(SplashActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// insertDummyContact();
//Toast.makeText(SplashScreen.this, " Permissions are l", Toast.LENGTH_SHORT).show();
LaunchApp();
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
finish();
}
}, 3000);
}
}
}
public void LaunchApp()
{
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
}
}
You need to call permissioncheck() on onCreate() method after setContentView(). Replace the code provided below with your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
permissioncheck();
}
I removed Handler codes on onCreate() method. Instead, use onRequestPermissionResult() and start LoginActivity from it. Replace the following code to your onRequestPermissionResult().
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// Here start the activity
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
Please carefully read comments in the code provided above.
Best Code
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public class Firstclass extends AppCompatActivity {
private int timeoutMillis = 5000;
/** The time when this {#link AppCompatActivity} was created. */
private long startTimeMillis = 0;
/** The code used when requesting permissions */
private static final int PERMISSIONS_REQUEST = 1234;
public int getTimeoutMillis() {
return timeoutMillis;
}
#SuppressWarnings("rawtypes")
public Class getNextActivityClass() {
return SecondActivity.class;
};
public String[] getRequiredPermissions() {
String[] permissions = null;
try {
permissions = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_PERMISSIONS).requestedPermissions;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (permissions == null) {
return new String[0];
} else {
return permissions.clone();
}
}
#TargetApi(23)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTimeMillis = System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= 23) {
checkPermissions();
} else {
startNextActivity();
}
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST) {
checkPermissions();
}
}
private void startNextActivity() {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
long delayMillis = getTimeoutMillis() - (System.currentTimeMillis() - startTimeMillis);
if (delayMillis < 0) {
delayMillis = 0;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Firstclass.this, getNextActivityClass()));
finish();
}
}, delayMillis);
}
private void checkPermissions() {
String[] ungrantedPermissions = requiredPermissionsStillNeeded();
if (ungrantedPermissions.length == 0) {
startNextActivity();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(ungrantedPermissions, PERMISSIONS_REQUEST);
}
}
}
#TargetApi(23)
private String[] requiredPermissionsStillNeeded() {
Set<String> permissions = new HashSet<String>();
for (String permission : getRequiredPermissions()) {
permissions.add(permission);
}
for (Iterator<String> i = permissions.iterator(); i.hasNext();) {
String permission = i.next();
if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " already granted.");
i.remove();
} else {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " not yet granted.");
}
}
return permissions.toArray(new String[permissions.size()]);
}
}
Manifest xml permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Application crashes every time camera open

I've written an application which should take picture and record video and then show it on the screen. When trying it on phone the camera won't work but works in emulator.
When executing the app this is what exactly happens:
Every time I clicked on the button to open the camera, the app stopped and the error it display is Appname has stopped, Open app again
When I clicked on Open app again it return to normal state
I have granted the camera permission in my program
below is my code:
public class EventActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
public static final String KEY_MENU_TYPE = "menutype";
//public static final String KEY_PREF_USER_DETAILS = "prefUserDetails";
private static final String TAG = EventActivity.class.getSimpleName();
private static final String SERVER_IMAGE_PATH = "http://edo.com/imageupload/";
private static final String SERVER_PATH = "http://edo.com/";
String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private EditText event, eventDescription, name;
private TextView attachmentStatus;
private static final int TAKE_PICTURE = 1;
private static final int PERMISSION_ALL = 3;
private Uri capturedImageUri;
private Uri videoUri;
private String mediaFile;
private String videoFile;
private static final int MY_SOCKET_TIMEOUT_MS = 5000;
private String[] serverData;
private static final int REQUEST_VIDEO_CAPTURE = 300;
private boolean isImage;
private String locationResult;
String menutype = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
Intent intent = getIntent();
/* ActionBar mBar = getSupportActionBar();
if(mBar != null){
mBar.setDisplayHomeAsUpEnabled(true);
}*/
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
mLocationRequest = createLocationRequest();
Button photoVideoButton = (Button)findViewById(R.id.take_image_video);
photoVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showOptionDialog();
}
});
attachmentStatus = (TextView)findViewById(R.id.file_status);
event = (EditText)findViewById(R.id.enter_event);
eventDescription =(EditText)findViewById(R.id.enter_event_description);
name = (EditText)findViewById(R.id.name);
Button cancelUploadButton = (Button) findViewById(R.id.cancel_upload);
assert cancelUploadButton != null;
cancelUploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resetViewControls();
}
});
Button sendToServerButton = (Button) findViewById(R.id.send_to_server);
assert sendToServerButton != null;
sendToServerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String eventValue = event.getText().toString().trim();
String eventDescriptionValue = eventDescription.getText().toString();
String nameValue = name.getText().toString();
String locationValue = "";
if(TextUtils.isEmpty(eventValue) || TextUtils.isEmpty(eventDescriptionValue) || TextUtils.isEmpty(nameValue)){
Toast.makeText(EventActivity.this, getString(R.string.send_to_server_error), Toast.LENGTH_LONG).show();
return;
}
if(locationResult == null || locationResult.equals("")){
locationValue = "";
}else{
locationValue = locationResult;
}
if(TextUtils.isEmpty(mediaFile) && TextUtils.isEmpty(videoFile)){
Toast.makeText(EventActivity.this, "Please attach a photo or video", Toast.LENGTH_LONG).show();
return;
}
if(!TextUtils.isEmpty(mediaFile) && isImage){
// send the information to remote server
Bitmap storeBitmap = BitmapFactory.decodeFile(mediaFile);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(storeBitmap, 640, 420, true);
String imageBasedString = convertBitmapToBaseImageString(resizedBitmap);
serverData = new String[]{eventValue, eventDescriptionValue, nameValue, imageBasedString, locationValue};
sendCapturedImageToServer(serverData);
//move stored video to a new folder
String photoPath = getMovedFilePath(mediaFile, eventValue);
moveFileToNewDestination(mediaFile, photoPath);
}else if(!TextUtils.isEmpty(mediaFile) && !isImage){
//Store the video to your server
uploadVideoToServer(videoFile, eventValue, eventDescriptionValue, nameValue, locationValue);
//move stored video to a new folder
String photoPath = getMovedFilePath(videoFile, eventValue);
moveFileToNewDestination(videoFile, photoPath);
}else{
// Image or video is missing. Show message to user
Toast.makeText(EventActivity.this, getString(R.string.upload_image_or_video), Toast.LENGTH_LONG).show();
}
}
});
this.menutype = intent.getStringExtra(KEY_MENU_TYPE);
if (this.menutype == null) {
this.menutype = "";
}
}
public void goBack(View view) {
Intent intent;
if (this.menutype.equals("PRE")) {
intent = new Intent(this, PreElectionMenuActivity.class);
} else if (this.menutype.equals("ACC")) {
intent = new Intent(this, AccreditationMenuActivity.class);
} else if (this.menutype.equals("ELE")) {
intent = new Intent(this, VotingMenuActivity.class);
} else if (this.menutype.equals("INC")) {
intent = new Intent(this, IncidentMenuActivity.class);
} else {
intent = new Intent(this, HomeActivity.class);
}
startActivity(intent);
}
private String getMovedFilePath(String filePath, String eventName){
int indexPosition = filePath.lastIndexOf(".");
String fileExtension = filePath.substring(indexPosition, filePath.length());
String newFilename = eventName + fileExtension;
return getFileDestinationPath(newFilename);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PICTURE) {
capturedImageUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = "";
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
Log.d(TAG, "Capture image path" + mediaFile);
attachmentStatus.setText("Image file has been attached");
isImage = true;
}
}
if (requestCode == REQUEST_VIDEO_CAPTURE) {
videoUri = data.getData();
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else{
videoFile = getRealPathFromURIPath(videoUri, EventActivity.this);
Log.d(TAG, "Captured video path " + videoUri);
Log.d(TAG, "New path " + videoFile);
attachmentStatus.setText("Video file has been attached");
isImage = false;
}
}
}
}
private void resetViewControls(){
event.setText("");
eventDescription.setText("");
name.setText("");
attachmentStatus.setText(R.string.attached_file);
}
#Override
protected void onResume() {
super.onResume();
if(capturedImageUri != null){
if (!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else {
mediaFile = getRealPathFromURIPath(capturedImageUri, EventActivity.this);
}
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
private String convertBitmapToBaseImageString(Bitmap bitmap){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
return Base64.encodeToString(byte_arr, 0);
}
private void sendCapturedImageToServer(String[] photoDetails){
Map<String, String> params = new HashMap<String,String>();
params.put("EVENT", photoDetails[0]);
params.put("EVENT_DESCRIPTION", photoDetails[1]);
params.put("NAME", photoDetails[2]);
params.put("CAPTURE_IMAGE", photoDetails[3]);
params.put("EVENT_LOCATION", photoDetails[4]);
GsonRequest<ServerObject> serverRequest = new GsonRequest<ServerObject>(
Request.Method.POST,
SERVER_IMAGE_PATH,
ServerObject.class,
params,
createRequestSuccessListener(),
createRequestErrorListener());
serverRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(EventActivity.this).addToRequestQueue(serverRequest);
}
private Response.Listener<ServerObject> createRequestSuccessListener() {
return new Response.Listener<ServerObject>() {
#Override
public void onResponse(ServerObject response) {
try {
Log.d(TAG, "Json Response " + response.getSuccess());
if(!TextUtils.isEmpty(response.getSuccess()) && response.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
};
};
}
private Response.ErrorListener createRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
public static void getAddressFromLocation(final double lat, final double lon, final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(lat, lon, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality() + ", " + address.getCountryName() ;
Log.d(TAG, "The converted Address " + result);
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to GeoCoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
#SuppressLint("HandlerLeak")
private class GeoCoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationResult = bundle.getString("address");
Log.d(TAG, "Location Result " + locationResult);
break;
default:
locationResult = null;
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.d(TAG, "Connection method has been called");
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
else{
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), EventActivity.this, new GeoCoderHandler());
}
}
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL: {
// If request is cancelled, the result arrays are empty.
if(grantResults[0] == PackageManager.PERMISSION_DENIED){
Toast.makeText(EventActivity.this, "Sorry!!!, you can't use this app without granting this permission", Toast.LENGTH_LONG).show();
finish();
}
if (grantResults[1] == PackageManager.PERMISSION_DENIED || grantResults[2] == PackageManager.PERMISSION_DENIED) {
// permission was denied, show alert to explain permission
showPermissionAlert();
}else{
//permission is granted. Get current location values
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
}
}
}
}
private void showPermissionAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permission_request_title);
builder.setMessage(R.string.app_permission_notice);
builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!hasPermissions(EventActivity.this, PERMISSIONS)){
ActivityCompat.requestPermissions(EventActivity.this, PERMISSIONS, PERMISSION_ALL);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(EventActivity.this, R.string.permission_refused, Toast.LENGTH_LONG).show();
}
});
builder.show();
}
protected LocationRequest createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private boolean isLocationEnabled(){
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
return false;
}
return true;
}
private void showLocationAlert(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_enable));
dialog.setPositiveButton(getResources().getString(R.string.network_location), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
EventActivity.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private void moveFileToNewDestination(String fromPath, String toPath){
File fromFile = new File(fromPath);
File toFile = new File(toPath);
if(!toFile.exists()){
try {
toFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fromStream = null;
FileOutputStream toStream = null;
try {
fromStream = new FileInputStream(fromFile);
toStream = new FileOutputStream(toFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] sourceByte = new byte[1024];
int index;
try {
while((index = fromStream.read(sourceByte)) > 0){
if (toStream != null) {
toStream.write(sourceByte, 0, index);
}
}
Log.d(TAG, "Video successfully moved to a new location");
} catch (IOException e) {
e.printStackTrace();
}
}
private String getFileDestinationPath(String filename){
String filePathEnvironment = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File directoryFolder = new File(filePathEnvironment + "/events/");
if(!directoryFolder.exists()){
directoryFolder.mkdir();
}
Log.d(TAG, "Full path " + filePathEnvironment + "/events/" + filename);
return filePathEnvironment + "/events/" + filename;
}
private void uploadVideoToServer(String pathToVideoFile, String eventName, String eventDescription, String eventCoverage, String eventLocation){
File videoFile = new File(pathToVideoFile);
RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);
RequestBody event = RequestBody.create(MediaType.parse("text/plain"), eventName);
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), eventDescription);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), eventCoverage);
RequestBody location = RequestBody.create(MediaType.parse("text/plain"), eventLocation);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create())
.build();
VideoInterface vInterface = retrofit.create(VideoInterface.class);
Call<ResultObject> serverCom = vInterface.uploadVideoToServer(vFile, event, description, name, location);
serverCom.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call, retrofit2.Response<ResultObject> response) {
ResultObject result = response.body();
if(!TextUtils.isEmpty(result.getSuccess()) && result.getSuccess().equals("1")){
Toast.makeText(EventActivity.this, getString(R.string.successful_upload), Toast.LENGTH_LONG).show();
resetViewControls();
}else{
Toast.makeText(EventActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
Log.d(TAG, "Error message " + t.getMessage());
}
});
}
private void showOptionDialog(){
final Dialog dialog = new Dialog(EventActivity.this);
dialog.setTitle("SELECT ACTION TO COMPLETE");
dialog.setContentView(R.layout.image_video_layout);
final TextView takePhoto = (TextView)dialog.findViewById(R.id.take_photo);
final TextView recordVideo = (TextView)dialog.findViewById(R.id.record_video);
dialog.show();
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Take a picture");
if(isLocationEnabled()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}else{
showLocationAlert();
}
dialog.dismiss();
}
});
recordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Record a video");
Intent videoCaptureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(videoCaptureIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(videoCaptureIntent, REQUEST_VIDEO_CAPTURE);
}
dialog.dismiss();
}
});
}
private boolean gps_enabled;
private boolean network_enabled;

android - onRequestPermissionsResult - does not override or implement a method from a supertype

I'm trying to implement Marshmallow's permission support in MyAdapter class for mylistView, but the method onRequestPermissionsResult does not override or implement a method from a supertype ... while I tried the code of Marshmallow's permission for WRITE_EXTERNAL_STORAGE to download file from internet in another project it was working well without this error "method does not override or implement a method from a supertype"
I'm using an Nexus 5X emulator running Android 8.1.0, API 27.
MyAdapter Class
public class MyAdapter extends BaseAdapter {
private static final int PERMISSION_REQUEST_CODE = 1;
String fileName;
String dirPath;
Context context;
ArrayList<StoryModel> TitleAndImage ;
ArrayList<StoryModel> forShowEachStoryInNewActivity ;
LayoutInflater inflter;
public MyAdapter(Context context, ArrayList<StoryModel> TitleAndImage ,ArrayList<StoryModel> forShowEachStoryInNewActivity) {
this.context = context;
this.TitleAndImage = TitleAndImage;
this.forShowEachStoryInNewActivity=forShowEachStoryInNewActivity;
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return TitleAndImage.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = inflter.inflate(R.layout.item_story, null);
TextView t1 = convertView.findViewById(R.id.title);
ImageView m1= convertView.findViewById(R.id.image);
Button b1 = convertView.findViewById(R.id.buttn_bwonload);
t1.setText(TitleAndImage.get(position).getTitle());
Picasso.get().load(TitleAndImage.get(position).getImage()).resize(200,200).into(m1);
//TODO : going to Show each story in new Activity
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ForEachStory.class);
String title = forShowEachStoryInNewActivity.get(position).getTitle();
// String image = forShowEachStoryInNewActivity.get(position).getImage();
String body = forShowEachStoryInNewActivity.get(position).getBody();
intent.putExtra("title", title);
// intent.putExtra("image", image);
intent.putExtra("body", body);
context.startActivity(intent);
}
});
//TODO download this story when i click on it's download button
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dirPath = com.example.abdullah.newstroynory.Utils.getRootDirPath(context);
String title_For_Download = forShowEachStoryInNewActivity.get(position).getTitle();
fileName = title_For_Download + ".mp3";
String audio_For_Download = forShowEachStoryInNewActivity.get(position).getAudio();
// String url = audio_For_Download;
//TODO Marshmallow's permission
if (Build.VERSION.SDK_INT >= 23)
{
if (checkPermission())
{
// Code for above or equal 23 API Oriented Device
// Your Permission granted already .Do next code
dorDownloadMyAudios ( fileName, dirPath , audio_For_Download);
} else {
requestPermission(); // Code for permission
}
}
else
{
// Code for Below 23 API Oriented Device
// Do next code
// dorDownloadMyAudios ( fileName, dirPath , audio_For_Download);
}
}
});
return convertView;
}
//TODO code of chick of download from the internet into the SD card
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText( context, "Write External Storage permission allows us to do store files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
//TODO library of downloading file
private void dorDownloadMyAudios ( String fileName, String dirPath , String url){
PRDownloader.initialize(context);
PRDownloaderConfig config = PRDownloaderConfig.newBuilder()
.setDatabaseEnabled(true)
.build();
PRDownloader.initialize(context, config);
int downloadId = PRDownloader.download(url, dirPath, fileName)
.build()
.setOnStartOrResumeListener(new OnStartOrResumeListener() {
#Override
public void onStartOrResume() {
}
})
.setOnPauseListener(new OnPauseListener() {
#Override
public void onPause() {
}
})
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel() {
}
})
.setOnProgressListener(new com.downloader.OnProgressListener() {
#Override
public void onProgress(Progress progress) {
}
})
.start(new OnDownloadListener() {
#Override
public void onDownloadComplete() {
// Log.d("--------->", "onCreate: "+dirPath+fileName);
Toast.makeText(context, "Hi", Toast.LENGTH_SHORT).show();
Log.d("------->", "onDownloadComplete: OK ------->");
}
#Override
public void onError(Error error) {
}
});
}
}
this another project it work well, download audio file without any error
MainActivity Class
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
String fileName;
String dirPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "https://firebasestorage.googleapis.com/v0/b/storynory-1e523.appspot.com/o/audio%2Fcroesus-solon-storynory.mp3?alt=media&token=3f4b9ff4-8891-4b8d-9ddf-1d461faf80c2";
dirPath = com.example.abdullah.dwonloadaudio.Utils.getRootDirPath(getApplicationContext());
fileName = "myPhoto2.mp3";
if (Build.VERSION.SDK_INT >= 23)
{
if (checkPermission())
{
// Code for above or equal 23 API Oriented Device
// Your Permission granted already .Do next code
dorDownloadMyAudios ( fileName, dirPath , url);
} else {
requestPermission(); // Code for permission
}
}
else
{
// Code for Below 23 API Oriented Device
// Do next code
}
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to do store files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
private void dorDownloadMyAudios (String fileName, String dirPath , String url){
PRDownloader.initialize(this);
PRDownloaderConfig config = PRDownloaderConfig.newBuilder()
.setDatabaseEnabled(true)
.build();
PRDownloader.initialize(getApplicationContext(), config);
int downloadId = PRDownloader.download(url, dirPath, fileName)
.build()
.setOnStartOrResumeListener(new OnStartOrResumeListener() {
#Override
public void onStartOrResume() {
}
})
.setOnPauseListener(new OnPauseListener() {
#Override
public void onPause() {
}
})
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel() {
}
})
.setOnProgressListener(new OnProgressListener() {
#Override
public void onProgress(Progress progress) {
}
})
.start(new OnDownloadListener() {
#Override
public void onDownloadComplete() {
Log.d("------->", "onDownloadComplete: OK ");
}
#Override
public void onError(Error error) {
}
});
}
}
note:the code is work before and after all override became deprecated
You can only override the onRequestPermissionsResult in a class that extends Activity or AppCompatActivity. More info here.

When first open camera I don't have permissions

I have problem with access to camera first time. I installed
my app. Next go to scan to QR Code. I use to scan QR Code google vision. App show dialog, which show about the permissions, next click "Allow",but camera doesn't open. But I go back activity and go to activity which scan QR Code, camera open.
my AdnroidManifest.xml
my class
public class ScanQrCodeActivity extends AppCompatActivity {
protected void attachBaseContext(Context context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(context));
}
private static final String TAG = "Barcode-reader";
// intent request code to handle updating play services if needed.
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private DatabaseHandler helper;
private TextView title_app;
private CameraSource mCameraSource;
private CameraSourcePreview mPreview;
private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
String passwordString, eightChars, barcodeString, decodedBarcodeValue, OTP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr_code);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
title_app = (TextView) findViewById(R.id.toolbar_title);
helper = new DatabaseHandler(this);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>) findViewById(R.id.graphicOverlay);
eightChars = getIntent().getStringExtra("eightChars");
passwordString = getIntent().getStringExtra("passwordString");
int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (rc == PackageManager.PERMISSION_GRANTED) {
createCameraSource();
} else {
requestCameraPermission();
}
Snackbar snackbar = Snackbar.make(mGraphicOverlay, R.string.zeskanuj_wygenerowany_kod, Snackbar.LENGTH_INDEFINITE);
View mView = snackbar.getView();
TextView mTextView = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
else
mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
snackbar.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.stage2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
findViewById(R.id.topLayout).setOnClickListener(listener);
Snackbar.make(mGraphicOverlay, "Aby móc wykryć Qr Koda potrzebny jest dostęp do kamery.",
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
#SuppressLint("InlinedApi")
private void createCameraSource() {
boolean autoFocus = false;
boolean useFlash = false;
Context context = getApplicationContext();
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
barcodeDetector.setProcessor(
new MultiProcessor.Builder<>(barcodeFactory).build());
barcodeFactory.setNewBarcodeListener(new BarcodeTrackerFactory.OnNewBarcodeListener() {
#Override
public void onNewItem(final Barcode item) {
Log.d("BarcodeFound", "Found new barcode! " + item.rawValue);
title_app.post(new Runnable() {
#Override
public void run() {
if (!barcodeDetector.isOperational())
{
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
Log.w(TAG, getString(R.string.low_storage_error));
}
}
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600, 1024)
.setRequestedFps(15.0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
builder = builder.setFocusMode(
autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
}
mCameraSource = builder
.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null)
.
build();
}
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
if (mPreview != null) {
mPreview.stop();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mPreview != null) {
mPreview.release();
}
}
private void startCameraSource() throws SecurityException {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
}
In your code immplement the following method
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 0:
boolean isPerpermissionForAllGranted = false;
if (grantResults.length > 0 && permissions.length==grantResults.length) {
for (int i = 0; i < permissions.length; i++){
if (grantResults[i] == PackageManager.PERMISSION_GRANTED){
isPerpermissionForAllGranted=true;
}else{
isPerpermissionForAllGranted=false;
}
}
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
isPerpermissionForAllGranted=true;
Log.e("value", "Permission Denied, You cannot use local drive .");
}
if(isPerpermissionForAllGranted){
// Fire here again for camera
createCameraSource();
}
break;
}
}
So what happens is When you fire the dialog for permission, you can implement the result method to come to know whether you were granted permission or not. So here you can check if the permission is granted for your permission request, You can again fire your method to open the camera.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission()
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_CALENDAR)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write calendar permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
References :
https://developer.android.com/training/permissions/requesting.html
https://www.sitepoint.com/requesting-runtime-permissions-in-android-m-and-n/
http://www.theappguruz.com/blog/runtime-permissions-in-android-marshmallow

How to get currently ongoing call duration after user ends a call in android?

I am calling from my app. After ends that call, I am trying to get a call duration. But my code return call duration two times. Last call duration while making call and new call duration after ends a call. But I need only one call duration after user ends the new call. How can i achieve this. Here is my code. Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final int CALL_PERMISSION= 99;
private static final int READ_LOG_PERMISSION=11;
Button btnGetCallDuration;
Context mContext;
private int mFlag = 0;
String phNumber = "";
boolean flag=false;
String callDuration = "";
public static int REQ_CODE=1;
private boolean callPermission=false;
private boolean readlogPermission=false;
public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
String[] permissions = new String[] {
Manifest.permission.READ_CALL_LOG,
Manifest.permission.CALL_PHONE,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
btnGetCallDuration = (Button) findViewById(R.id.btnGetCallDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissions();
}
btnGetCallDuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("onclick", "called");
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:121"));
startActivity(intent);
//flag = true;
}
});
}
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(mContext,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("request code",requestCode+"\t"+resultCode);
if(requestCode==REQ_CODE)
{
Log.v("request code",requestCode+"");
// getCallDruation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permissions granted.
callPermission=true;
} else {
// no permissions granted.
callPermission=false;
}
return;
}
}
}
#Override
protected void onPause() {
super.onPause();
Log.v("Pause is called","pause");
flag=true;
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CALL_PHONE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
}
return false;
} else {
return true;
}
}
public boolean readCallLogPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_CALL_LOG)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CALL_LOG},
READ_LOG_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
READ_LOG_PERMISSION);
}
return false;
} else {
callPermission=true;
return callPermission;
}
}
#Override
protected void onResume() {
super.onResume();
Log.v("flag","onrsume called");
if(flag)
{
getCallDruation();
flag=false;
}
}
private void getCallDruation() {
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Log.v("get duration","called");
Cursor cur = getContentResolver().query(contacts, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");
int number = cur.getColumnIndex(CallLog.Calls.NUMBER);
int duration = cur.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details : \n");
while (cur.moveToNext()) {
phNumber = cur.getString(number);
callDuration = cur.getString(duration);
sb.append("\nPhone Number:" + phNumber+"\t"+callDuration);
break;
}
cur.close();
String str = sb.toString();
Log.v("restult",str);
Toast.makeText(mContext, phNumber + "\t\t" + callDuration, Toast.LENGTH_SHORT).show();
}
}
This above code is called from onResume() life cycle method of activity.

Categories

Resources