利用BroadCastReceiver实现service与acvitity之间的通信(线程倒计时)

public class MainActivity extends AppCompatActivity {
    private TextView tv_number;
    private Button btn_start;
    private MyBroadReciver reciver=null;

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

        //⑦程序创建时实例化自定义广播解析者
        reciver=new MyBroadReciver();

        tv_number= (TextView) findViewById(R.id.tv_number);
        btn_start= (Button) findViewById(R.id.btn_start);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //①启动跳转到service
                turnService();
            }
        });
    }



    //定义跳转到service的方法
    private void turnService(){
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
    }

    /**
     * ⑥定义广播接收者,重写onReceive方法
     */
    class MyBroadReciver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String mes=intent.getStringExtra("count");
            tv_number.setText(mes);
        }
    }

    /**
     * ⑧开始接收广播时动态获取权限
     */
    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.work.test310.MainAcvitity");
        registerReceiver(reciver,filter);
    }

    /**
     * ⑨结束广播时释放资源,解除绑定
     */
    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(reciver);
    }
public class MyService extends Service {
    private MyThread thread=null;
    public static int i=10;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * ③重写onStartCommand方法
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //⑤在service中实例化并开启线程
        if(thread==null){
            thread=new MyThread();
            thread.start();
        }
        return super.onStartCommand(intent, flags, startId);

    }

    /**
     * ④自定义线程类,设置倒计时的线程方法
     */
    class MyThread extends Thread{
        @Override
        public void run() {
            while (i>=0){
                Intent intent=new Intent("com.work.test310.MainAcvitity");
                intent.putExtra("count",String.valueOf(i));
                sendBroadcast(intent);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i--;
            }

            super.run();
        }
    }
上一篇:Android跳转系统设置Settings的各个界面


下一篇:每日日报