在应用结算中共享首选项以记住付费项

时间:2018-02-06 11:12:37

标签: android sharedpreferences

我正在创建一个Android应用,我希望通过使用应用内结算库销售一些视频。我添加了应用内结算并且它正在运行,但如果我购买视频并退回或退出应用程序,视频将再次付费意味着我需要再次购买。所以我想,如果一个用户购买视频,他可以永久地观看它。我从Android Developer" https://developer.android.com/training/data-storage/shared-preferences.html#java"但它不起作用。请根据我的准则提供帮助。这是我的代码。谢谢。 共享首选项代码根据我的知识和帮助是:

SharedPreferences sp = getPreferences(MODE_PRIVATE);
if (hasUserBought){ // The user bought your video, so save the value now
    sp.edit().putBoolean("key_here", true).apply();
}

的onCreate()

boolean videoBought = sp.getBoolean"key_here", false);
if (videoBought){
    ... //user bought the video already
}
else {
... //user hasn't bought it yet
}

但是关键在哪里。

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlaybackControlView;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.zeeshan.echoshow.util.IabHelper;
import com.zeeshan.echoshow.util.IabResult;
import com.zeeshan.echoshow.util.Inventory;
import com.zeeshan.echoshow.util.Purchase;

import org.w3c.dom.Text;

public class DetailsActivity extends AppCompatActivity {
    private MediaController vidControl;
    TextView description;
    ImageButton mPlayButton;
    TextView movienamedetails;
    TextView movieCategory;
    ImageView imageCover;
    TextView movieDuration;
    Button purchasebutton;
    TextView movieYear;
    private static final String TAG = "MainActivity";
    private final String STATE_RESUME_WINDOW = "resumeWindow";
    private final String STATE_RESUME_POSITION = "resumePosition";
    private final String STATE_PLAYER_FULLSCREEN = "playerFullscreen";

    private SimpleExoPlayerView mExoPlayerView;
    private MediaSource mVideoSource;
    private boolean mExoPlayerFullscreen = false;
    private FrameLayout mFullScreenButton;
    private ImageView mFullScreenIcon;
    private Dialog mFullScreenDialog;
    ListView list;
    private int mResumeWindow;
    private long mResumePosition;
    TextView freepaid_check;

   String ITEM_SKU_temba1="om.qshow.temba1";
   String ITEM_SKU_temba2="com.qshow.temba2";
    String ITEM_SKU_temba3="com.qshow.temba3";
    String ITEM_SKU_Arab_Twit="com.qshow.arabtwit";
    String ITEM_SKU_Dinar="com.qshow.dinar";
    String ITEM_SKU_Khaybar="com.qshow.khaybar";
    String ITEM_SKU_Malhamat_Ghadr="com.qshow.malhamatghadr";
    String ITEM_SKU_Malhamat_Dhad="com.qshow.malhamatdhad";
    String ITEM_SKU_Soukout_Khilafa="com.qshow.soukoutkhilafa";
    String ITEM_SKU_Swalef="com.qshow.swalef";
    String ITEM_SKU_Malhamt_Sakhra="com.qshow.malhamtsakhra";

    String ITEM_SKU=null;
    String movie_name;
    private static final String TAG1 =
            "InAppBilling";
    IabHelper mHelper;
    private Button buyButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_details);
//        Intent intent = getIntent();
//        final String[] parts_array = intent.getStringArrayExtra("parts_array");
        if (savedInstanceState != null) {
            mResumeWindow = savedInstanceState.getInt(STATE_RESUME_WINDOW);
            mResumePosition = savedInstanceState.getLong(STATE_RESUME_POSITION);
            mExoPlayerFullscreen = savedInstanceState.getBoolean(STATE_PLAYER_FULLSCREEN);
        }
        if (mExoPlayerView == null) {

            mExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.myVideo);
            initFullscreenDialog();
            initFullscreenButton();
            final Intent intent = getIntent();
            final String[] parts_array = intent.getStringArrayExtra("parts_array");
//            final int[] parts_images_array=intent.getIntArrayExtra("parts_images_array");
            description = (TextView) findViewById(R.id.tv_description_detail);
            imageCover = (ImageView) findViewById(R.id.imagecoverdetails);
            movienamedetails = (TextView) findViewById(R.id.movienamedetails);
            movieCategory = (TextView) findViewById(R.id.moviecategorty);
            movieDuration = (TextView) findViewById(R.id.movieDuration);
            movieYear = (TextView) findViewById(R.id.moviedate);
            buyButton = (Button)findViewById(R.id.buyButton);
//            clickButton = (Button)findViewById(R.id.clickButton);
//            clickButton.setEnabled(false);
            int image = intent.getIntExtra("image", 0);
            String desc_detail = intent.getStringExtra("description_details");
             movie_name = intent.getStringExtra("moviename_details");
            String movie_category = intent.getStringExtra("movie_category");
            String movie_durationz = intent.getStringExtra("movie_duration");
            String movie_time = intent.getStringExtra("movie_year");
            String free_or_paid=intent.getStringExtra("free_or_paid");
            freepaid_check = (TextView) findViewById(R.id.tv_freepaid);
            // String vidAddress = intent.getStringExtra("movie_links");
//            Custom_Parts_Adapter adapter = new Custom_Parts_Adapter(DetailsActivity.this, parts_array, image);
//            grid=(GridView)findViewById(R.id.grid_parts);
//
////            if(!free_or_paid.equals("paid"))
////            {
////                grid.setVisibility(View.GONE);
////                freepaid_check.setVisibility(View.VISIBLE);
////
////            }
//            grid.setAdapter(adapter);
//            grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view,
//                                        int position, long id) {
//                    Intent intent1 = new Intent(DetailsActivity.this, PartVideo.class);
//                    startActivity(intent1);
//                   // Toast.makeText(DetailsActivity.this, "You Clicked on " +parts_array[+ position], Toast.LENGTH_SHORT).show();
//
//
//                }
//            });

            Custom_Parts_Adapter adapter=new Custom_Parts_Adapter(this, parts_array, image);
            list=(ListView)findViewById(R.id.list);
            if(!free_or_paid.equals("Free"))
            {
                list.setVisibility(View.GONE);
                buyButton.setVisibility(View.VISIBLE);

            }
            list.setAdapter(adapter);
            list.setOnTouchListener(new ListView.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = event.getAction();
                    switch (action) {
                        case MotionEvent.ACTION_DOWN:
                            // Disallow ScrollView to intercept touch events.
                            v.getParent().requestDisallowInterceptTouchEvent(true);
                            break;

                        case MotionEvent.ACTION_UP:
                            // Allow ScrollView to intercept touch events.
                            v.getParent().requestDisallowInterceptTouchEvent(false);
                            break;
                    }

                    // Handle ListView touch events.
                    v.onTouchEvent(event);
                    return true;
                }
            });
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(DetailsActivity.this, PartVideo.class);
                    intent.putExtra("episode_url",parts_array[position]);
//                    Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
                    startActivity(intent);
                }
            });

//            int image = intent.getIntExtra("image", 0);
            String vidAddress = intent.getStringExtra("movie_links");
            imageCover.setImageResource(image);

            description.setText(desc_detail);

            movienamedetails.setText(movie_name);

            movieCategory.setText(movie_category);

            movieDuration.setText(movie_durationz);
            movieYear.setText(movie_time);

            DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("Echo Shoow");
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
            Uri vidUri = Uri.parse(vidAddress);

            mVideoSource = new ExtractorMediaSource(vidUri, dataSourceFactory, extractorsFactory,null,null);
        }

        initExoPlayer();

        if (mExoPlayerFullscreen) {
            ((ViewGroup) mExoPlayerView.getParent()).removeView(mExoPlayerView);
            mFullScreenDialog.addContentView(mExoPlayerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mFullScreenIcon.setImageDrawable(ContextCompat.getDrawable(DetailsActivity.this, R.drawable.ic_fullscreen_skrink));
            mFullScreenDialog.show();
        }
        // imageView = (VideoView) findViewById(R.id.myVideo);
        //  final String vidAddress = "https://www.rmp-streaming.com/media/bbb-360p.mp4";
//        Uri vidUri = Uri.parse(vidAddress);
//        imageView.setVideoURI(vidUri);
//        mPlayButton = (ImageButton) findViewById(R.id.play_button);
//        mPlayButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                imageView.start();
//                // hide button once playback starts
//                mPlayButton.setVisibility(View.GONE);
//            }
//        });
//        String fullScreen =  getIntent().getStringExtra("fullScreenInd");
//        if("y".equals(fullScreen)) {
//            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            getSupportActionBar().hide();
//        }
//        vidControl = new MediaController(this);
//        vidControl.setAnchorView(imageView);
        // imageView.setMediaController(vidControl);
        //imageView.setVideoURI("https://www.rmp-streaming.com/media/bbb-360p.mp4","https://www.rmp-streaming.com/media/bbb-360p.mp4");



        String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsNH7KIemSXJuQOaPQLpjEjLISNiAjNxnNoFeLIW7bYEqo+ODrg1ALBvxA0viiaidWnphuwfuORYruLSLcGTQrbPcNV1EYcxrDyrnt5W0Qcv+xgnTTMikuZPlAM+3wBQp7Neipudam1lN04WYrxaxWPtBYgw92cCGflxSJXPLwS5LEdIxFH7j9i6P+EiF0aBK29swIo0XvRnYHGn9aIMZ2lZMxMhFfR2mLoTt+inw7KGV0NTLoVSMPxFZuo9f+im8Uw73Ku2Xzf4KswV4D8Y6kJKr7cXwC7wFXIAGQoQbRsfptOUR8zmMYuGmOTi1FCZmBrfrR+JrXGNb4nnTqNx2YwIDAQAB";
        mHelper = new IabHelper(this, base64EncodedPublicKey);

        mHelper.startSetup(new
                                   IabHelper.OnIabSetupFinishedListener() {
                                       public void onIabSetupFinished(IabResult result) {
                                           if (!result.isSuccess()) {
                                               Log.d(TAG1, "In-app Billing setup failed: " +
                                                       result);
                                           } else {
                                               Log.d(TAG1, "In-app Billing is set up OK");
                                           }
                                       }
                                   });
    }

//    public void buttonClicked (View view)
//    {
//        clickButton.setEnabled(false);
//        buyButton.setEnabled(true);
//    }

    public void buyClick(View view) {

        if(movie_name.equals("Temba 1")||movie_name.equals("تمبة 1"))
        {
            ITEM_SKU=ITEM_SKU_temba1;
        }
        if(movie_name.equals("Temba 2")||movie_name.equals("تمبة 2"))
        {
            ITEM_SKU=ITEM_SKU_temba2;
        }
        if(movie_name.equals("Temba 3")||movie_name.equals("تمبة 3"))
        {
            ITEM_SKU=ITEM_SKU_temba3;
        }
        if(movie_name.equals("Dinar")||movie_name.equals("دينار"))
        {
            ITEM_SKU=ITEM_SKU_Dinar;
        }
        if(movie_name.equals("Malhamat Ghadr")||movie_name.equals("ملحمة الغدر"))
        {
            ITEM_SKU=ITEM_SKU_Malhamat_Ghadr;
        }
        if(movie_name.equals("Soukout Khilafa")||movie_name.equals("سقوط الخلافة"))
        {
            ITEM_SKU=ITEM_SKU_Soukout_Khilafa;
        }
        if(movie_name.equals("Malhamat Dhad")||movie_name.equals("ملحمة الضاد"))
        {
            ITEM_SKU=ITEM_SKU_Malhamat_Dhad;
        }
        if(movie_name.equals("Sawalef")||movie_name.equals("سوالف بوبخيت"))
        {
            ITEM_SKU=ITEM_SKU_Swalef;
        }
        if(movie_name.equals("Arab Twit")||movie_name.equals("عرب تويت"))
        {
            ITEM_SKU=ITEM_SKU_Arab_Twit;
        }
        if(movie_name.equals("Khaybar")||movie_name.equals("خيبر"))
        {
            ITEM_SKU=ITEM_SKU_Khaybar;
        }
        if(movie_name.equals("Malhamt Sakhra")||movie_name.equals("ملحمة صخرة"))
        {
            ITEM_SKU=ITEM_SKU_Malhamt_Sakhra;
        }


        mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
                mPurchaseFinishedListener, "purchase_token");
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data)
    {
        if (!mHelper.handleActivityResult(requestCode,
                resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
            = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result,
                                          Purchase purchase)
        {
            if (result.isFailure()) {
                // Handle error
                return;
            }
            else if (purchase.getSku().equals(ITEM_SKU)) {
                consumeItem();
                buyButton.setEnabled(false);
            }

        }
    };
    public void consumeItem() {
        mHelper.queryInventoryAsync(mReceivedInventoryListener);
    }

    IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
            = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result,
                                             Inventory inventory) {

            if (result.isFailure()) {
                // Handle failure
            } else {
                mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
                        mConsumeFinishedListener);
            }
        }
    };

    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
            new IabHelper.OnConsumeFinishedListener() {
                public void onConsumeFinished(Purchase purchase,
                                              IabResult result) {

                    if (result.isSuccess()) {
                        list.setVisibility(View.VISIBLE);
                    } else {
                        // handle error
                    }
                }
            };

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



    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putInt(STATE_RESUME_WINDOW, mResumeWindow);
        outState.putLong(STATE_RESUME_POSITION, mResumePosition);
        outState.putBoolean(STATE_PLAYER_FULLSCREEN, mExoPlayerFullscreen);

        super.onSaveInstanceState(outState);
    }


    private void initFullscreenDialog() {

        mFullScreenDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) {
            public void onBackPressed() {
                if (mExoPlayerFullscreen)
                    closeFullscreenDialog();
                super.onBackPressed();
            }
        };
    }


    private void openFullscreenDialog() {

        ((ViewGroup) mExoPlayerView.getParent()).removeView(mExoPlayerView);
        mFullScreenDialog.addContentView(mExoPlayerView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mFullScreenIcon.setImageDrawable(ContextCompat.getDrawable(DetailsActivity.this, R.drawable.ic_fullscreen_skrink));
        mExoPlayerFullscreen = true;
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        mFullScreenDialog.show();
    }


    private void closeFullscreenDialog() {

        ((ViewGroup) mExoPlayerView.getParent()).removeView(mExoPlayerView);
        ((FrameLayout) findViewById(R.id.video_frame)).addView(mExoPlayerView);
        mExoPlayerFullscreen = false;
        mFullScreenDialog.dismiss();
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mFullScreenIcon.setImageDrawable(ContextCompat.getDrawable(DetailsActivity.this, R.drawable.ic_fullscreen_expand));
    }


    private void initFullscreenButton() {

        PlaybackControlView controlView = (PlaybackControlView) mExoPlayerView.findViewById(R.id.exo_controller);
        mFullScreenIcon = (ImageView) controlView.findViewById(R.id.exo_fullscreen_icon);
        mFullScreenButton = (FrameLayout) controlView.findViewById(R.id.exo_fullscreen_button);
        mFullScreenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mExoPlayerFullscreen) {
                    openFullscreenDialog();
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    closeFullscreenDialog();}
            }
        });
    }


    private void initExoPlayer() {

        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
        LoadControl loadControl = new DefaultLoadControl();
        SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this), trackSelector, loadControl);
        mExoPlayerView.setPlayer(player);

        boolean haveResumePosition = mResumeWindow != C.INDEX_UNSET;

        if (haveResumePosition) {
            mExoPlayerView.getPlayer().seekTo(mResumeWindow, mResumePosition);
        }

        mExoPlayerView.getPlayer().prepare(mVideoSource);
        mExoPlayerView.getPlayer().setPlayWhenReady(true);
    }


    @Override
    protected void onResume() {

        super.onResume();


    }


    @Override
    protected void onPause() {

        super.onPause();

        if (mExoPlayerView != null && mExoPlayerView.getPlayer() != null) {
            mResumeWindow = mExoPlayerView.getPlayer().getCurrentWindowIndex();
            mResumePosition = Math.max(0, mExoPlayerView.getPlayer().getContentPosition());

            mExoPlayerView.getPlayer().release();
        }

        if (mFullScreenDialog != null)
            mFullScreenDialog.dismiss();

    }

}

0 个答案:

没有答案