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就完畢了。

。。






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM