android中利用service和广播实现多个activity共享计时器

  • 需求:
    • 需要在activityA中开始计时,然后在activityB和activityC中操作,并且需要在Activity A、B、C中都要看到计时器
  • 效果如下:
    *在这里插入图片描述
  • 思路
    1、创建service,并在service初始化的时候开始计时
    2、在开始计时以后,每秒发送一次广播,把秒数广播出去
    3、在需要显示的页面注册广播,拿到广播中的数据并展示出来

最主要的一个类就是TimerService

public class TimerService extends Service {

    private Timer timer = null;
    private TimerTask timerTask = null;
    private int i = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        //在创建service的时候开始计时
        if(timer==null&&timerTask==null){
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    i++;
                    //没执行一次就发送一次广播
                    Intent intent = new Intent();
                    intent.putExtra("time",i);
                    intent.setAction("com.demo.timer");
                    sendBroadcast(intent);
                }
            };
            timer.schedule(timerTask,0,1000);
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(timerTask!=null){
            timerTask.cancel();
            timerTask=null;
        }
        if(timer!=null){
            timer.cancel();
            timer=null;
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

在ActivityA中的代码如下

public class AActivity extends AppCompatActivity implements View.OnClickListener {

    protected TextView tv;
    protected Button btnStart;
    protected Button btnStop;
    protected Button btnJumpToB;
    private TimerReceiver timerReceiver=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_a);
        initView();
        getSupportActionBar().setTitle("A");
        //注册广播
        timerReceiver = new TimerReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.demo.timer");
        registerReceiver(timerReceiver, filter);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_start) {
            if(timerReceiver==null){
                timerReceiver = new TimerReceiver();
                IntentFilter filter = new IntentFilter();
                filter.addAction("com.demo.timer");
                registerReceiver(timerReceiver, filter);
            }
            //开始服务
            startService(new Intent(this, TimerService.class));
        } else if (view.getId() == R.id.btn_stop) {
        	//停止服务
            stopService(new Intent(this, TimerService.class));
            //注销广播
            unregisterReceiver(timerReceiver);
            timerReceiver=null;
        } else if (view.getId() == R.id.btn_jumpToB) {
            Intent intent = new Intent(this, BActivity.class);
            startActivity(intent);
            finish();
        }
    }

    //内部类,实现TimerReceiver
    public class TimerReceiver extends BroadcastReceiver {
        //必须要重载的方法,用来监听是否有广播发送
        @Override
        public void onReceive(Context context, Intent intent) {
            String intentAction = intent.getAction();
            if (intentAction.equals("com.demo.timer")) {
                int time = intent.getIntExtra("time", 0);
                tv.setText(time + "");
            }
        }
    }
    private void initView() {
        tv = (TextView) findViewById(R.id.tv);
        btnStart = (Button) findViewById(R.id.btn_start);
        btnStart.setOnClickListener(AActivity.this);
        btnStop = (Button) findViewById(R.id.btn_stop);
        btnStop.setOnClickListener(AActivity.this);
        btnJumpToB = (Button) findViewById(R.id.btn_jumpToB);
        btnJumpToB.setOnClickListener(AActivity.this);
    }
}

activityA中布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".timerActivity.AActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_margin="5dp"
        android:textSize="20dp"
        android:textColor="@color/black"/>

    <Button
        android:id="@+id/btn_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开始"/>

    <Button
        android:id="@+id/btn_stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="结束"/>

    <Button
        android:id="@+id/btn_jumpToB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转"/>

</LinearLayout>

activityB中的代码与A类似,所以我就不贴了。

  • 最后,别忘了在 AndroidManifest.xml中声明
 <service android:name=".timerActivity.TimerService"
            android:enabled="true"
            android:exported="true">
 </service>

项目地址如下:
https://download.csdn.net/download/ljp345775/12251527

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljp345775

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值