Android-五子连珠(四)-MainActivity的Java代码

package com.example.administrator.wuziqi;


import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private boolean music=true;
   ImageButton ismusic;
    MediaPlayer mediaPlayer1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //播放背景音乐
        mediaPlayer1 = null;
        mediaPlayer1 = MediaPlayer.create(this, R.raw.a2);
        mediaPlayer1.start();

        //设置循环播放
        mediaPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer1.start();
                mediaPlayer1.setLooping(true);
            }
        });

        //用声音小图标来暂停和播放音乐
        ismusic=(ImageButton) findViewById(R.id.music);
        ismusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(music)
                {
                    mediaPlayer1.pause();
                    ismusic.setBackgroundResource(R.drawable.music1);
                    music=false;
                }
                else
                {
                    mediaPlayer1.start();
                    ismusic.setBackgroundResource(R.drawable.music);
                    music=true;
                }
            }
        });


        //利用button图标来触发悔棋和重新开局函数
        final wuziqipan jj=(wuziqipan) findViewById(R.id.wuziqipan);
        ImageButton button=(ImageButton) findViewById(R.id.Huiqi);
        ImageButton button1=(ImageButton) findViewById(R.id.Replay);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jj.Huiqi();
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jj.GameAgain();
            }
        });


    }

    //实现再按一次退出程序
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}


你可能感兴趣的:(android学习笔记)