Unable to read checkDeviceAdminPermission - java

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.

Related

Google billing API automatically refunding in-app purchases even after being aknowledged

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);
}
}

Replacing a button to go a paid layout with a swiping motion

I am building an app. One of the features I have is a paid option in which the user has access to an additional layout. Right now, the user can get there by clicking a button. Instead, I would like to have a swiping motion- if the user swipes down, it will ask for permission for the paid layout. If they do pay, when they swipe up, they can access the original layout.
Here is my main activity :
public class MainActivity extends AppCompatActivity {
EditText editText2;
Button btn_purchase;
ImageView imageView2;
String skuId;
SessionManager sessionManager;
// create new Person
private BillingClient mBillingClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionManager=new SessionManager(MainActivity.this);
if(sessionManager.getPurchased()){
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
btn_purchase=findViewById(R.id.btn_purchase);
imageView2 = (ImageView) findViewById(R.id.imageView2);
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(int responseCode, #Nullable List<Purchase> purchases) {
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (Purchase purchase : purchases) {
//TODO: Handle purchase
// handlePurchase(purchase);
Log.e("Main", "handle Purchase ");
Log.e("MainAct", "onPurchasesUpdated() response: " + responseCode);
Log.e("dev", "successful purchase...");
String purchasedSku = purchase.getSku();
Log.e("dev", "Purchased SKU: " + purchasedSku);
String purchaseToken = purchase.getPurchaseToken();
sessionManager.savePurchased(true);
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
} else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
} else {
// Handle any other error codes.
}
}
}).build();
List<String> skuList = new ArrayList <> ();
skuList.add("appsubscription2018");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
mBillingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
// Process the result.
if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
Log.e("MainActivity", "onSkuDetailsResponse: success");
for (SkuDetails skuDetails : skuDetailsList) {
Log.e("MainActivity", "products: "+skuDetailsList);
String sku = skuDetails.getSku();
skuId = skuDetails.getSku();
String price = skuDetails.getPrice();
if ("appsubscription2018 ".equals(sku)) {
Log.e("MainActivity", "product is appsubscription2018 ");
// mPremiumUpgradePrice = price;
}
}
}
}
});
btn_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponseCode) {
if (billingResponseCode == BillingClient.BillingResponse.OK) {
// The billing client is ready. You can query purchases here.
// The billing client is ready. You can query purchases here.
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku("appsubscription2018")
.setType(BillingClient.SkuType.INAPP)
.build();
int responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
if (responseCode != BillingClient.BillingResponse.OK) {
Log.e("Main", "launchBillingFlow ok");
}
}
}
#Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkFilePermission(MainActivity.this)){
getPhoto();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode ==1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkFilePermission(final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
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.READ_EXTERNAL_STORAGE}, 1);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);{
getPhoto();
}
}
}
}

Why my Activity is not called in onResume

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();
}
}
}

Pause music when phone receives any incoming calls, home button is pressed and when phone screen goes off(lockscreen)

while playing music using this mediaplayer, whenever a call comes, home button is pressed and lockscreen appears and on return to the app after the above problems...the play button in the app doesnt respond....I want to pause the music untill I return to the app and should continue playing from where it had stopped......plz help...
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable,View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play",Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
#Override
protected void onPause()
{
super.onPause();
if (play3!= null)
{
play3.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if ((play3 != null) && (!play3.isPlaying())) {
but32.setText("Play");
but32.setOnClickListener(this);
}
}
This helped me to overcome my problems.....I'm able to play the music which gets paused when home button/lockscreen/calls appears...from where it had stopped

Android SDK how to OnClickListener

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

Categories