Как убрать кнопку после покупки - PullRequest
1 голос
/ 06 октября 2019

Пожалуйста, помогите !!! Я создаю приложение для захвата экрана, и проблема в том, что после нажатия кнопки PRO и после покупки реклама и кнопка не скрываются.

Я пытаюсь удалить кнопку и рекламу, используя изменения макета:

setContentView (R.layout.main_pro)
the code:

IabHelper.OnIabPurchaseFinishedListener () {
@Override
public void onIabPurchaseFinished (IabResult result, purchase purchase) {
if (result.isFailure ()) {
Log.d (TAG, "Purchase Error:" result);
return;
}
even if (purchase.getSku (). equals (SKU_REMOVE_ADS)) {
isAdsDisabled = true;
setContentView (R.layout.main_pro);
remove ads ();
Toast.makeText (MainActivity.this, “The purchase was successful,” Toast.LENGTH_LONG) .show ();
}
}
};
}
Full code:

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.icu.text.SimpleDateFormat;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import com.davidgrigoryan.screenrecorder.util.Constants;
import com.davidgrigoryan.screenrecorder.util.IabHelper;
import com.davidgrigoryan.screenrecorder.util.IabResult;
import com.davidgrigoryan.screenrecorder.util.Inventory;
import com.davidgrigoryan.screenrecorder.util.Purchase;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE = 1000;
    private int mScreenDensity;
    File file;
    private Context context;
    private ShareActionProvider mShareActionProvider;
    private MediaProjectionManager mProjectionManager;
    private static final int DISPLAY_WIDTH = 720;
    private static final int DISPLAY_HEIGHT = 1280;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    static final String SKU_REMOVE_ADS = "android.test.purchased";
    static final int RC_REQUEST = 10111;
    private MediaProjectionCallback mMediaProjectionCallback;
    private MediaRecorder mMediaRecorder;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final int REQUEST_PERMISSION_KEY = 1;
    boolean isRecording = false;
    private FloatingActionButton rec;

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    private Intent intent;
    private Activity activity;
    private boolean URL_TO_SHARE;
    private ImageView wm;
    private NotificationManagerCompat notificationManager;
    private String title;
    private String message;
    private InterstitialAd mInterstitialAd;
    private String testDeviceId;
    AdRequest adRequest;
    private AdView adView;
    IabHelper mHelper;
    String base64EncodedPublicKey = "PublicKey";
    Boolean isAdsDisabled = false;
    String payload = "Upgrade PRO";
    private Inventory i;
    private IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
    private static boolean isWidget = false;
    private static Context appContext;
    private Timer timer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView pro = (ImageView) findViewById(R.id.buy);
        final SharedPreferences prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
        pro.setVisibility(prefs.getBoolean("isPurchase", true) ? View.VISIBLE : View.INVISIBLE);
        pro.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                purchaseRemoveAds();
            }
        });
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final Handler handler = new Handler();
        final Timer timer = new Timer();
        final TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        if (mInterstitialAd.isLoaded()) {
                            mInterstitialAd.show();
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 120000);
        adView = (AdView) findViewById(R.id.adView);
        adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        AdView adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId("ca-app-pub-9842509861911521/3646081879");
        AdRequest adRequestInterstitial = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice(testDeviceId)
                .build();
        AdRequest adRequestBanner = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice(testDeviceId)
                .build();
        AdRequest request = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .build();
        AdSize adSize = new AdSize(320, 50);
        MobileAds.initialize(getApplicationContext(), "ca-app-pub-9842509861911521/3646081879");
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-9842509861911521/1961271598");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                // Load the next interstitial.
                mInterstitialAd.loadAd(new AdRequest.Builder().build());
            }

        });
        String[] PERMISSIONS = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
        };
        if (!Service.hasPermissions(this, PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
        }
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;

        mMediaRecorder = new MediaRecorder();

        mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        rec = (FloatingActionButton) findViewById(R.id.rec);
        rec.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onToggleScreenShare();
            }
        });
        mHelper = new IabHelper(this, base64EncodedPublicKey);
        mHelper.enableDebugLogging(false);
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            @Override
            public void onIabSetupFinished(IabResult result, IabHelper.QueryInventoryFinishedListener mGotInventoryListener) throws IabHelper.IabAsyncInProgressException {
                Log.d(TAG, "Setup finished.");

                if (!result.isSuccess()) {
                    return;
                }
                if (mHelper == null)
                    return;
                Log.d(TAG, "Setup successful. Querying inventory.");
                mHelper.queryInventoryAsync(mGotInventoryListener);
            }
        });
        queryPurchased();

        IabHelper.OnIabPurchaseFinishedListener mPurchasedFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
            @Override
            public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
                if (result.isFailure()) {
                    Log.d(TAG, "Error purchasing: " + result);
                    return;
                }
                else if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
                    isAdsDisabled = true;
                    setContentView(R.layout.main_pro);
                    removeAds();
                    Toast.makeText(MainActivity.this,"Purchase successful",Toast.LENGTH_LONG).show();
                }
            }
        };
    }
    private void queryPurchased() {
        IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
            @Override
            public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
                if (result.isFailure()) {
                    // handle error here
                }
                else{
                    // does the user have the premium upgrade?
                    isAdsDisabled = inventory.hasPurchase(SKU_REMOVE_ADS);
                    // update UI accordingly
                }
            }
        };
    }
    public void purchaseRemoveAds() {
        try {

            mHelper.flagEndAsync();
            mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, 9, mPurchaseFinishedListener, "SECURITYSTRING");
        } catch (Exception e) {
            e.printStackTrace();

            mHelper.flagEndAsync();
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle(R.string.error)
                    .setMessage(R.string.error_play_store)
                    .setPositiveButton("OK", null)
                    .show();
        }
        IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
            public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
                Log.d(TAG, "Purchase finished: " + result + ", purchase: "
                        + purchase);

                if (mHelper == null)
                    return;

                if (result.isFailure()) {
                    return;
                }
                if (!verifyDeveloperPayload(purchase)) {
                    return;
                }
                if (isAdsDisabled == true){
                    setContentView(R.layout.main_pro);
                }

                Log.d(TAG, "Purchase successful.");

                if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
                    removeAds();
                }
            }
        };
    }

    private void removeAds() {
        adView.setEnabled(false);
        adView.setVisibility(View.INVISIBLE);
    }
    public void onToggleScreenShare() {
        if (!isRecording) {
            Toast.makeText(getApplicationContext(), R.string.start_rec, Toast.LENGTH_LONG).show();
            startService();
            initRecorder();
            shareScreen();
        } else {
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            } else {
                Log.d("TAG", "Ads not loaded!");
            }
            Toast.makeText(getApplicationContext(), R.string.stop_rec, Toast.LENGTH_LONG).show();
            stopService();
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            stopScreenSharing();
        }
    }

    private void shareScreen() {
        if (mMediaProjection == null) {
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
            return;
        }
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
        isRecording = true;
    }

    private VirtualDisplay createVirtualDisplay() {
        return mMediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
    }

    private void initRecorder() {
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //THREE_GPP
            mMediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
            mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
            mMediaRecorder.setVideoFrameRate(16); // 30
            mMediaRecorder.setVideoEncodingBitRate(3000000);
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            int orientation = ORIENTATIONS.get(rotation + 90);
            mMediaRecorder.setOrientationHint(orientation);
            mMediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("NewApi")
    private File initFile() {
        File dir = new File(Environment.getExternalStorageDirectory() +
                File.separator + "ScreenRecorder");


        if (!dir.exists() && !dir.mkdirs()) {
            Log.wtf(TAG,
                    R.string.error_folder
                            + dir.getAbsolutePath());
            file = null;
        } else {
            file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
                    "'VIDEO-'yyyyMMddHHmmss'.mp4'").format(new Date()));
        }
        return file;
    }

    private void stopScreenSharing() {
        if (mVirtualDisplay == null) {
            return;
        }
        mVirtualDisplay.release();
        destroyMediaProjection();
        isRecording = false;
    }


    private void destroyMediaProjection() {
        if (mMediaProjection != null) {
            mMediaProjection.unregisterCallback(mMediaProjectionCallback);
            mMediaProjection.stop();
            mMediaProjection = null;
        }
        Log.i(TAG, "MediaProjection Stopped");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != REQUEST_CODE) {
            Log.e(TAG, "Unknown request code: " + requestCode);
            return;
        }
        if (resultCode != RESULT_OK) {
            Toast.makeText(this, R.string.denied, Toast.LENGTH_SHORT).show();
            isRecording = false;
            return;
        }
        Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
        } else
            Log.d(TAG, "onActivityResult handled by IABUtil.");

        mMediaProjectionCallback = new MediaProjectionCallback();
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
        mMediaProjection.registerCallback(mMediaProjectionCallback, null);
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
        isRecording = true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_KEY: {
                if ((grantResults.length > 0) && (grantResults[0] + grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
                    onToggleScreenShare();
                } else {
                    isRecording = false;
                    Snackbar.make(findViewById(android.R.id.content), R.string.message,
                            Snackbar.LENGTH_INDEFINITE).setAction(R.string.enable,
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                                    startActivity(intent);
                                }
                            }).show();
                }
                return;
            }
        }
    }

    private class MediaProjectionCallback extends MediaProjection.Callback {
        @Override
        public void onStop() {
            if (isRecording) {
                isRecording = false;
                mMediaRecorder.stop();
                mMediaRecorder.reset();
            }
            mMediaProjection = null;
            stopScreenSharing();
        }
    }

    @Override
    public void onPause() {
        if (adView != null) {
            adView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (adView != null) {
            adView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (mHelper != null)
            try {
                mHelper.dispose();
                mHelper = null;

            } catch (IabHelper.IabAsyncInProgressException e) {
                e.printStackTrace();
            }
        if (adView != null) {
            adView.destroy();
        }
        super.onDestroy();
        destroyMediaProjection();
    }

    private void about() {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setTitle(R.string.about);
        builder1.setMessage(R.string.description);
        builder1.setCancelable(true);
        builder1.setNeutralButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert11 = builder1.create();
        alert11.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @SuppressLint("ResourceType")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.about:
                about();
                return true;
            case R.id.share:
                shareApp();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void shareApp() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
        String extraText = getString(R.string.share_desc, getString(R.string.link));
        intent.putExtra(Intent.EXTRA_TEXT, extraText);
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
    }

    public void startService() {
        Intent serviceIntent = new Intent(this, Background.class);
        serviceIntent.putExtra("inputExtra", "Notification");

        ContextCompat.startForegroundService(this, serviceIntent);
    }

    public void stopService() {
        Intent serviceIntent = new Intent(this, Background.class);
        stopService(serviceIntent);
    }

    boolean verifyDeveloperPayload(Purchase p) {
        String payload = p.getDeveloperPayload();
        return true;
    }
}

И это выглядит так:

enter image description here

Что я делаю не так? Как я могу это исправить?

Спасибо за любую помощь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...