BroadcastReceiverコールバックを簡単に実現
8111 ワード
UpMainData
public interface UpMainData {
String Start();
String Stop();
}
MyReceiver04, UpMainData
public class MyReceiver04 extends BroadcastReceiver implements UpMainData{ @Override public void onReceive(Context context, Intent intent) { String key = intent.getStringExtra("key"); if(key.equals("1")){ Start(); } if(key.equals("2")){ Stop(); } } @Override public String Start() { //
String a=" "; return a; } @Override public String Stop() { String a=" "; return a; } }
private Button bt,bt1; private TextView tv; private MyReceiver04 receiver04; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt=(Button)findViewById(R.id.bt); bt1=(Button)findViewById(R.id.button); tv=(TextView)findViewById(R.id.textView);
// , , receiver04=new MyReceiver04(); IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction("UpdateUI"); registerReceiver(receiver04,intentFilter); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(); intent.putExtra("key","1"); intent.setAction("UpdateUI"); sendBroadcast(intent); String a = receiver04.Start(); tv.setText(a); } }); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(); intent.putExtra("key","2"); intent.setAction("UpdateUI"); sendBroadcast(intent); String a = receiver04.Stop(); tv.setText(a); } }); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver04); }