package com.zdsoft.broadcastreceiverdynamic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* 动态注册广播
* 代码中动态的指定广播地址并注册
* 特点:非常驻型的,广播会跟随程序的生命周期。
*/
public class MainActivity extends AppCompatActivity {
private Button bt;
private EditText et;
private DynamicReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new DynamicReceiver();
bt = (Button) findViewById(R.id.bt);
et = (EditText) findViewById(R.id.et);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.zdsoft.receiver.MESSAGE");
intent.putExtra("msg", "我是消息发送者");
sendBroadcast(intent);
}
});
}
/**
* 在onStart()中注册广播
*/
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.zdsoft.receiver.MESSAGE");
registerReceiver(receiver, intentFilter);
}
/**
* 在onStop()中解除注册广播
*/
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
/**
* 创建广播,新建一个内部类,继承自BroadcastReceiver,并重写onRecive()方法
*/
public class DynamicReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, final Intent intent) {
new CountDownTimer(12000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.i("******", intent.getStringExtra("msg") + millisUntilFinished / 1000);
et.setText(intent.getStringExtra("msg") + millisUntilFinished / 1000);
}
@Override
public void onFinish() {
Log.i("******", "结束");
et.setText("结束");
}
}.start();
}
}
}