zoukankan      html  css  js  c++  java
  • Android实现后台长期监听时间变化

    1.首先我们的目的是长期监听时间变化,事实上应用程序退出。

    通过了解我们知道注冊ACTION_TIME_TICK广播接收器能够监听系统事件改变,可是

    查看SDK发现ACTION_TIME_TICK广播事件仅仅能动态注冊:

    Broadcast Action: The current time has changed. Sent every minute. You can not receive this through components declared in manifests, only by exlicitly registering for it with Context.registerReceiver().

    所以要想实现长期监听时间变化。就须要借助后台服务的帮助了

    2.解决方法(3步骤):

    (1)在某个时间启动后台服务

    package com.example.broadcastreceiverofdatachange;

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;

    public class MainActivity extends Activity {

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

    //启动后台服务
    Intent service=new Intent(this, TimeService.class);
    startService(service);

    }

    }

    (2)在服务组件中动态注冊广播事件

    package com.example.broadcastreceiverofdatachange;

    import android.app.Service;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.util.Log;

    public class TimeService extends Service {

    @Override
    public IBinder onBind(Intent intent) {

    return null;
    }

    @Override
    public void onCreate() {

    super.onCreate();
    Log.i("liujun", "后台进程被创建。

    。。

    ");

    //服务启动广播接收器,使得广播接收器能够在程序退出后在后天继续运行。接收系统时间变更广播事件
    DataChangeReceiver receiver=new DataChangeReceiver();
    registerReceiver(receiver,new IntentFilter(Intent.ACTION_TIME_TICK));

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i("liujun", "后台进程。。

    。");
    return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {

    Log.i("liujun", "后台进程被销毁了。。。

    ");
    super.onDestroy();
    }

    }

    (3)在广播接收器组件中操作

    package com.example.broadcastreceiverofdatachange;


    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.util.Log;


    public class DataChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

    Log.i("liujun", "时间发生变化。。。

    ");

    }


    }


    //至此长期实现后台监听时间变化Demo就完毕了。

    。。





  • 相关阅读:
    深入浅出SQL教程之Group by和Having
    AFNetworking3.0 Https P12证书
    C#访问注册表
    One reason for not able to show chinese correctly in installation
    Debugging DLL loading issues with GFLAGS
    RegistryFree COM Registration
    RegistrationFree COM Interop
    net use
    MS UI Automation原来如此
    取景器的视野率和放大倍率
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5245810.html
Copyright © 2011-2022 走看看