guys I need help with this code :
public View.OnClickListener btnGetLastLocationOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
};
so what I want to do is when I click on btnGetLocation this code should work, but instead the code works automatically when I start the activity so how can I make works only when I click on the button ?
I hope you guys understand the problem, I'm new Android developer so I'm still learning forgive me for my stupid question.
thank you
*** Update :
here is the whole code :
TextView txtmylink;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Button getlastlocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtmylink = (TextView) findViewById(R.id.mylink);
getlastlocation = (Button) findViewById(R.id.getlastlocation);
getlastlocation.setOnClickListener(getlastlocationOnClickListener);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
View.OnClickListener getlastlocationOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(MainActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
};
private void getMyLocation() {
try {
/* code should explicitly check to see if permission is available
(with 'checkPermission') or explicitly handle a potential 'SecurityException'
*/
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
txtmylink.setText(String.valueOf("http://maps.google.com/maps?q=") +
String.valueOf(mLastLocation.getLatitude()) +
String.valueOf(",")+ String.valueOf(mLastLocation.getLongitude()));
} else {
Toast.makeText(MainActivity.this,
"mLastLocation == null",
Toast.LENGTH_LONG).show();
}
} catch (SecurityException e) {
Toast.makeText(MainActivity.this,
"SecurityException:\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
getMyLocation();
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(MainActivity.this,
"onConnectionSuspended: " + String.valueOf(i),
Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(MainActivity.this,
"onConnectionFailed: \n" + connectionResult.toString(),
Toast.LENGTH_LONG).show();
}
}
That's because you haven't associated the View.onClickListener object you've written to anything yet. Thus when the activity is started the listener's code gets executed. When you want a specific view say 'A' to respond to a click, you associate a View.onClickListener to it. So in your case add the following.
yourbutton.setOnClickListener(btnGetLastLocationOnClickListener)
Make sure you've bound the yourbutton to the Button view.
try this :
public void onClick(View v) {
if (view.getId() == R.id.btnGetLocation)
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
If still not works write your code like this :
your activity must implement OnClickListener and
btnGetLocation.setOnClickListener(this)
and you will have the onClick like this
public void onClick(View v) {
if (view.getId() == R.id.btnGetLocation)
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
You can accomplish it using the following code
btnGetLocation = (Button) findViewById(R.id.btnGetLocation); // or whatever you called the button
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
}
Note that you can add this code in the onCreate() method to make it work
Related
I tried looking at previous questions and answers but with no luck finding a real solution. I'm acknowledging purchases once they are processed although my users are still automatically refunded. Below is my whole purchase activity. It's a simple activity with a big button to purchase the app's full version. Anoter button to restore previous purchases. A third button to show some advice if users were not able to restore their purchase.
Any help would be appreciated!
public class BuyActivity extends AppCompatActivity {
Button unlock_button;
Button restore_purchase;
static final String PRODUCT_ID = "full_version";
private BillingClient billingClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy);
unlock_button = findViewById(R.id.unlock_button);
restore_purchase = findViewById(R.id.restore_purchase);
billingClient = BillingClient.newBuilder(getApplicationContext())
.setListener((billingResult, list) -> {
// responds to all purchases that were already made
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK && list!= null) {
for (Purchase purchase:list){
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
acknowledge_purchase(purchase);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
features_unlocked();
}
},500);
} else {
Toast.makeText(getApplicationContext(), "ERROR OCCURRED", Toast.LENGTH_SHORT).show();
}
}
} else if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED && list!=null) {
features_unlocked();
} else {
Toast.makeText(getApplicationContext(), "ERROR OCCURRED", Toast.LENGTH_SHORT).show();
}
})
.enablePendingPurchases()
.build();
connect_to_google();
restore_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restore_purchase();
}
});
unlock_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//launch_purchase_flow(productDetailsList.get(0));
Toast.makeText(getApplicationContext(), "CAN'T START THE PURCHASE PROCESS", Toast.LENGTH_SHORT).show();
}
});
}
void features_unlocked(){
App.get().MyTheme = 1;
Intent i = new Intent(BuyActivity.this, Unlocked_celebration.class);
startActivity(i);
finish();
}
void connect_to_google(){
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
get_product_details(); // download all details to different variables as you want
Log.i( "appName", String.format( "billing setup response code %s", billingResult.toString() ) );
}
}
#Override
public void onBillingServiceDisconnected() {
connect_to_google();
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
//show products available to buy
void get_product_details(){
List<String> productIds = new ArrayList<>();
productIds.add("full_version");
SkuDetailsParams params = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(
params,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK && list!=null){
if (list.size()>0) {
Log.println(Log.DEBUG,"TAG", "onSkuDetailsResponse: " + list.get(0).getPrice());
unlock_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
BuyActivity.this,
BillingFlowParams.newBuilder().setSkuDetails(list.get(0)).build()
);
}
});
}
}
}
}
);
}
void acknowledge_purchase(Purchase purchase){
AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams
.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
#Override
public void onAcknowledgePurchaseResponse(#NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
}
}
});
}
void restore_purchase(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
connect_to_google();
new Handler().post(new Runnable() {
#Override
public void run() {
billingClient.queryPurchasesAsync(
BillingClient.SkuType.INAPP,
new PurchasesResponseListener() {
#Override
public void onQueryPurchasesResponse(#NonNull BillingResult billingResult, #NonNull List<Purchase> list) {
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK) {
for (Purchase purchase: list){
if (purchase.getPurchaseState()==Purchase.PurchaseState.PURCHASED
&& !purchase.isAcknowledged()) {
acknowledge_purchase(purchase);
features_unlocked();
} else if (purchase.getPurchaseState()==Purchase.PurchaseState.PURCHASED) {
features_unlocked();
}
}
} else if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) {
features_unlocked();
}
}
}
);
}
});
}
},300);
}
protected void onResume() {
super.onResume();
restore_purchase();
}
#Override
protected void onStop() {
super.onStop();
if (billingClient != null) billingClient.endConnection();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
if (billingClient != null) billingClient.endConnection();
billingClient=null;
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
if (billingClient != null) billingClient.endConnection();
}
public void cantRestore(View v){
Intent i = new Intent(BuyActivity.this, RestorePurchase.class);
startActivity(i);
}
}
I've been trying to program a working shop system for days, but I see that the Billing Client is not connected.
Toast message here is error connecting to billing.
Where is the mistake?
Do I need a help class? In many instructions it is said that you can use a help classe but do not have to.
With which possibility one can execute to each article another code if the Aktikel was bought?
I would like to offer six digital products that the user can buy.
thank you for your help.
Here is my ShopActivity.class code:
public class ShopActivity extends AppCompatActivity implements PurchasesUpdatedListener {
private BillingClient billingClient;
Button loadProdukt;
RecyclerView recyclerProdukt;
// IabHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
// String base64EncodedPublicKey = "_BASE64_KEY_";
// mHelper = new IabHelper(this, base64EncodedPublicKey);
// TODO 01.07.2019 IabHelper?
setupBillingClient();
loadProdukt = findViewById(R.id.btn_load_produkt);
recyclerProdukt = findViewById(R.id.recycler_view_paket);
recyclerProdukt.setHasFixedSize(true);
recyclerProdukt.setLayoutManager(new LinearLayoutManager(this));
// event
loadProdukt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(billingClient.isReady()){
SkuDetailsParams params = SkuDetailsParams.newBuilder()
.setSkusList(Arrays.asList("10_coins","20_coins","30_coins","40_coins","80_coins","200_coins"))
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
if (billingResult.getResponseCode() == BilllingResonse.OK) {
loadProduktToRecyclerView(skuDetailsList);
}else{
Toast.makeText(ShopActivity.this, "Cannot query product", Toast.LENGTH_SHORT).show();
}
}
});
}else{
Toast.makeText(ShopActivity.this, "Billing not ready", Toast.LENGTH_SHORT).show();
}
}
});
}
private void loadProduktToRecyclerView(List<SkuDetails> skuDetailsList) {
ProduktAdapter adapter = new ProduktAdapter(this, skuDetailsList,billingClient);
recyclerProdukt.setAdapter(adapter);
}
private void setupBillingClient() {
// billingClient = BillingClient.newBuilder(this).enablePendingPurchases().setListener(this).build();
billingClient = BillingClient.newBuilder(this).setListener(this).build();
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BilllingResonse.OK) {
Toast.makeText(ShopActivity.this, "Success to connect Billing", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(ShopActivity.this, "Error not connect to Billing", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBillingServiceDisconnected() {
Toast.makeText(ShopActivity.this, "You are disconnect.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
// if user click Buy, we will retrieve data here
Toast.makeText(this, "Purchase item: "+purchases.size(), Toast.LENGTH_SHORT).show();
if (billingResult.getResponseCode() == BillingResponse.OK && purchases != null) {
for ( Purchase purchases : purchases) {
handlePurchase (purchases);
}
}else if (billingResult.getResponseCode() == BillingResponse.USER_CANCELED) {
}else{
}
}
}
AIDL is deprecated use Google Play Billing Library
I have followed the official documentation from here to display the location dialog to the user as our app doesn't work without location. The problem is that even when I press the OK button on the dialog, sometimes the onFailure of the task listener gets called, more importantly, even when onSuccess(LocationSettingsResponse locationSettingsResponse) does get called, I'm unable to immediately get the location details, the workaround I made is to create a separate thread to get the details in a loop. I need to know a simpler method to do this.
This took me over 2 days time and I still can't figure what's wrong in my code.
FusedLocationProviderClient client;
TextView textView;
boolean started = false;
double lat = 0;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
client = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(tag, "no perm");
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
} else
work();
}
void work() {
if (!isLocationEnabled()) createLocationRequest();
else locationDetails();
}
int t = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e(tag, "activity result");
work();
}
void locationDetails() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
client.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
if(lat!=0)return;
lat = location.getLatitude();
textView.setText("location: lat" + lat + " lng" + location.getLongitude());
Log.e(tag, "happy");
} else {
repeatedRequests();
Log.e(tag, "null location");
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
} else work();
}
void createLocationRequest() {
final LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
final SettingsClient settingsclient = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = settingsclient.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
repeatedRequests();
Log.e(tag, "success");
}
});
task.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException) {
Log.e(tag, "failure" + e.getLocalizedMessage());
// repeatedRequests();
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
Log.e(tag, "erorr " + sendEx.getLocalizedMessage());
// Ignore the error.
}
}
}
});
}
void repeatedRequests() {
if (!started) {
started = true;
Log.e(tag, "Thread started");
new Thread(new Runnable() {
#Override
public void run() {
while (lat == 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
t++;
if (t > 50) break;
Log.e(tag, "repeat");
runOnUiThread(new Runnable() {
#Override
public void run() {
locationDetails();
}
});
}
}
}).start();
}
}
boolean isLocationEnabled() {
int locationMode = 0;
try {
locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}
Try to set mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
just for yours samsung, in my case it works but keep in the mind that locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) will return false in this case.
getLastLocation()
it works when there is at least one subscriber to the google service..
You need to subscribe, and if you do not need to constantly update the coordinates, you can immediately unsubscribe...
val client = LocationServices.getFusedLocationProviderClient(this)
client.requestLocationUpdates(locationRequest, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
//job.invoke()
client.removeLocationUpdates(this)
}
}, Looper.myLooper())
Button reqDeviceAdmin;
reqDeviceAdmin = (Button) findViewById(R.id.reqDeviceAdmin);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
if (!checkUsageStatsPermission(RequestPermission.this)) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
}
if (checkDeviceAdminPermission(RequestPermission.this)){
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_active));
} else {
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_not_active));
}
reqDeviceAdmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkDeviceAdminPermission(RequestPermission.this)) {
} else {
requestDeviceAdmin();
}
}
});
#Override
public void onResume() {
super.onResume();
if (checkDeviceAdminPermission(RequestPermission.this)) {
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_active));
} else {
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_not_active));
}
}
This code is not checking for the if(checkDeviceAdminPermission(RequestPermission.this)) condition to be true. It's always returning else condition.It's always fetching the text uninstall_protect_is_not_active. This code is in RequestPermission.java. MIN_SDK=21.
I am using exactly same app and i am using this type:
#RequiresApi(api = Build.VERSION_CODES.M)
public void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck =getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
If you call the checkBTpermission any where you can getting permission.
Application that worked yesterday does not work today. I'm still not understanding what I'm doing wrong. The problem is, I'm calling the following code fragment, but I can not activate it. What is the problem?
Edit1:
Toast works but why does not the particle in it work?
public class PermissionsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permissions);
}
#Override
protected void onStart() {
super.onStart();
initWidget();
}
private void initWidget() {
Button permission = (Button) findViewById(R.id.permission);
permission.setOnClickListener(this);
Button accessibility = (Button) findViewById(R.id.accessibility);
accessibility.setOnClickListener(this);
LinearLayout permissionLayout = (LinearLayout) findViewById(R.id.permission_layout);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
permissionLayout.setVisibility(View.GONE);
} else {
permissionLayout.setVisibility(View.VISIBLE);
}
}
private void goToPassword() {
if (SharedPreferenceUtil.readIsNumModel()) {
startActivity(new Intent(this, NumberCheckActivity.class));
finish();
} else {
startActivity(new Intent(this, GestureCheckActivity.class));
finish();
}
SharedPreferenceUtil.editIsFirst(false);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ToastUtils.showToast("Permission allowed.");
} else {
ToastUtils.showToast("Please allow permission");
}
return;
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.permission:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2909);
} else {
}
} else {
ToastUtils.showToast("Success");
}
break;
case R.id.accessibility:
if (!MyConstants.isPermissionOk(PermissionsActivity.this)) {
PermissionsActivity.this.startActivity(new Intent("android.settings.USAGE_ACCESS_SETTINGS"));
ToastUtils.showToast("Please find App Locker in this menu and enable it.");
} else {
ToastUtils.showToast("Accessibility enabled");
}
break;
default:
break;
}
}
protected void onResume() {
super.onResume();
goToNextScreen();
}
private void goToNextScreen() {
if (Build.VERSION.SDK_INT >= 23) {
if (MyConstants.isPermissionOk(PermissionsActivity.this) && Settings.System.canWrite(this)) {
goToPassword();
}
}
ToastUtils.showToast("onResume Working?");
}
}
Problem Fixed - Check it out best solution:
public class PermissionsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permissions);
}
#Override
protected void onStart() {
super.onStart();
initWidget();
}
private void initWidget() {
Button permission = (Button) findViewById(R.id.permission);
permission.setOnClickListener(this);
Button accessibility = (Button) findViewById(R.id.accessibility);
accessibility.setOnClickListener(this);
LinearLayout permissionLayout = (LinearLayout) findViewById(R.id.permission_layout);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
permissionLayout.setVisibility(View.GONE);
} else {
permissionLayout.setVisibility(View.VISIBLE);
}
}
private void goToPassword() {
if (SharedPreferenceUtil.readIsNumModel()) {
startActivity(new Intent(this, NumberCheckActivity.class));
finish();
} else {
startActivity(new Intent(this, GestureCheckActivity.class));
finish();
}
SharedPreferenceUtil.editIsFirst(false);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ToastUtils.showToast("Permission allowed.");
} else {
ToastUtils.showToast("Please allow permission");
}
return;
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.permission:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2909);
} else {
ToastUtils.showToast("Success");
}
} else {
ToastUtils.showToast("Success");
}
break;
case R.id.accessibility:
if (!MyConstants.isPermissionOk(PermissionsActivity.this)) {
PermissionsActivity.this.startActivity(new Intent("android.settings.USAGE_ACCESS_SETTINGS"));
ToastUtils.showToast("Please find App Locker in this menu and enable it.");
} else {
ToastUtils.showToast("Accessibility enabled");
}
break;
default:
break;
}
}
protected void onResume() {
super.onResume();
goToNextScreen();
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void goToNextScreen() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (MyConstants.isPermissionOk(PermissionsActivity.this) && checkIfAlreadyhavePermission() ) {
goToPassword();
}
}else{
goToPassword();
}
}
}