Android Studioインターフェースの一例

2891 ワード

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