不管是 按鍵、藍芽、GPS...等,都一定要實作。
但 CallBack 能夠自定義裡面的傳輸內容嗎?
答案是可以的。
最常見的例子 : 跑背景、非同步執行...等。
這裡就舉簡單的範例,利用 Button 去觸發
1 . 回傳格式介面
public interface HelloCallBack {
    public void success(String strSuccess);
    
}
2 . 回傳內容設定
public class Hello {
    public HelloCallBack _helloCallBack;
    public Hello(HelloCallBack helloCallBack){
        this._helloCallBack = helloCallBack;    
    }
    
    public void speak(){
        // 回傳內容
        _helloCallBack.success(""+(int)(Math.random()*42+1));
    }
    
}
3 . 如果有被 CallBack 觸發(可改為計時),TextView就會被更新
public class MainActivity extends Activity implements OnClickListener, HelloCallBack{
    private TextView textView1;
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView1 = (TextView) findViewById(R.id.textView1);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        new Hello(this).speak();
    }
    @Override
    public void success(String strSuccess) {
        textView1.setText(strSuccess);        
    }
}
歡迎轉載,請註明出處。
 
沒有留言:
張貼留言