首页 > 代码库 > Android实现后台长期监听时间变化
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就完成了。。。