Android Studio Interface一例

1. 修改MainActivity.java

package ai.nixie.smartmailbox;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity implements OnMailDelivery{

    SmartMailbox smartMailbox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        smartMailbox = new SmartMailbox(this);
    }
    @Override
    public int onMailDelivery() {
        //邮递员来送信了的时候触发此事件
        Log.e("Mailman", "I just delivered a few mails to your mailbox!");
        return 3;
    }
    public void button1(View view) {
        smartMailbox.StartMonitoring();
    }
}

2. 新建一个Interface文件OnMailDelivery.java

package ai.nixie.smartmailbox;

/**
 * Created by aidenfang on 4/5/18.
 */

public interface OnMailDelivery {
    int onMailDelivery();
}

3. 新建一个SmartMailbox

package ai.nixie.smartmailbox;

import android.util.Log;

/**
 * Created by aidenfang on 4/5/18.
 */

public class SmartMailbox {

    OnMailDelivery robot;

    public SmartMailbox(OnMailDelivery listener) {
        this.robot = listener;
    }

    public void StartMonitoring() {
        Log.e("NOTE: ", "Monitoring Started!");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (robot.onMailDelivery()>0) {
            Log.e("NEW MAIL ALERT ->>", "You have " + robot.onMailDelivery() + " new mails");
        }else {
            Log.e("NEW MAIL ALERT ->>", "You don't have mails!");
        }
    }
}

4. 修改res/layout/activity_main.xml




    

5. 运行

点击按钮,查看logcat.

E/NOTE:: Monitoring Started!
E/Mailman: I just delivered a few mails to your mailbox!
E/Mailman: I just delivered a few mails to your mailbox!
E/NEW MAIL ALERT ->>: You have 3 new mails

你可能感兴趣的:(Android Studio Interface一例)