我在服务中创建了广播接收器,这个广播接收器频繁运行。但我想每隔一小时运行一次这个广播接收器。没有令人不安的服务。有什么建议吗?
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
AppLockApplication.getInstance().getlocationprovider().connect();
telephonyManager.listen(null, PhoneStateListener.LISTEN_CALL_STATE);
siminfoMap = SimInfo.getSimInfo(telephonyManager,getApplicationContext());
Log.e(TAG,"-----SIM INFO STATUS------\n");
for (String keyvalue : siminfoMap.keySet()){
Log.i(TAG,"SimInfo : "+keyvalue +" : "+siminfoMap.get(keyvalue));
}
Intent batteryStatus = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
HealthModel healthModel=new HealthModel();
healthinfo_Map = new HashMap<String, JSONObject>();
//Bettary status
int level= batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
int plugged= batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,0);
boolean present= batteryStatus.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
int scale= batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
int status= batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS,0);
String technology= batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
int temperature= batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);
int voltage= batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
int remaing = -1;
if (level >= 0 && scale > 0) {
remaing =scale-level;
}
Log.e(TAG,"-----BATTERY STATUS-----\n");
batteryinfoMap= new HashMap<String, String>();
batteryinfoMap.put("Plugged",String.valueOf(plugged));
batteryinfoMap.put("Present",String.valueOf(present));
batteryinfoMap.put("Battaery Present Percentage", String.valueOf(level));
batteryinfoMap.put("Battaery Remaining Percentage", String.valueOf(remaing));
batteryinfoMap.put("Battaery Total Percentage", String.valueOf(scale));
for (String keyset : batteryinfoMap.keySet()){
Log.i(TAG,"Battery Info : "+keyset+" : "+batteryinfoMap.get(keyset));
}
if(status==1){
batteryinfoMap.put("Charging Status","Unknown");
}else if(status==2){
batteryinfoMap.put("Charging Status","Charging");
}else if(status==3){
batteryinfoMap.put("Charging Status","Discharging");
}else if(status==4){
batteryinfoMap.put("Charging Status","Not Charging");
}else if(status==5){
batteryinfoMap.put("Charging Status","Full");
}
batteryinfoMap.put("Temperature",String.valueOf(temperature));
batteryinfoMap.put("Technology",technology );
batteryinfoMap.put("Voltage",String.valueOf(voltage));
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//Memory status
memoryInfo = new ActivityManager.MemoryInfo();
manager.getMemoryInfo(memoryInfo);
memory_info = new HashMap<String,String>();
memory_info.put(" AvailableMemory",String.valueOf(memoryInfo.availMem ));
memory_info.put(" LowMemory",String.valueOf(memoryInfo.lowMemory));
memory_info.put(" threshold",String.valueOf(memoryInfo.threshold));
memory_info.put(" Totalmemory",String.valueOf(memoryInfo.totalMem));
Log.e(TAG,"-----RAM STATUS-----\n");
for (String keyString : memory_info.keySet()){
Log.i(TAG,"Memory Info : "+keyString +" :"+memory_info.get(keyString));
}
//External memory info :
extrenal_memory = new HashMap<String,String>();
Log.e(TAG,"-----EXTERNAL MEMORY STATUS-----\n");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
long bytesAvailable = (long)stat.getBlockSizeLong() * (long)stat.getAvailableBlocksLong();
long tot=(long)stat.getBlockSizeLong()*(long)stat.getBlockCountLong();
extrenal_memory.put("Totalsize",String.valueOf(tot));
extrenal_memory.put("Availablesize",String.valueOf(bytesAvailable));
for (String keyset : extrenal_memory.keySet()){
Log.i(TAG,"External Memory : "+keyset+" : "+extrenal_memory.get(keyset));
}
}else {
Log.i(TAG,"No SD card");
}
//Internal memory info :
internal_memory = new HashMap<String,String>();
Log.e(TAG,"-----INTERNAL MEMORY STATUS-----\n");
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSizeLong();
long availableBlocks = stat.getAvailableBlocksLong();
long totalBlocks = stat.getBlockCountLong();
long avilablemem=(availableBlocks*blockSize);
long totalmem=(totalBlocks*blockSize);
internal_memory.put("Totalsize",String.valueOf(totalmem));
internal_memory.put("Availablesize",String.valueOf(avilablemem));
for (String keyset : internal_memory.keySet()){
Log.i(TAG,"Internal Memory : "+keyset+" : "+internal_memory.get(keyset));
}
InfoMap = new HashMap<String, String>();
// WIFI status
if(wifiInfo.getType() == ConnectivityManager.TYPE_MOBILE){
InfoMap.put("Wifi Type","Mobile Wifi Connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_WIFI){
InfoMap.put("Wifi Type","WIFI data connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_WIMAX){
InfoMap.put("Wifi Type"," WiMAX data connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_ETHERNET){
InfoMap.put("Wifi Type","Ethernet data connection");
}else if(wifiInfo.getType() == ConnectivityManager.TYPE_BLUETOOTH){
InfoMap.put("Wifi Type","Bluetooth data connection");
}else {
InfoMap.put("Wifi Type","Other NewWork");
}
InfoMap.put("Wifi-Roaming",String.valueOf(wifiInfo.isRoaming()));
InfoMap.put("Wifi-SignalInfo",String.valueOf(wifiInfo.isAvailable()));
InfoMap.put("Wifi-State",String.valueOf(wifiInfo.getState()));
//Mobile status :
if(String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("EDGE")){
InfoMap.put("MobileType","2G");
}else if(String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("HSDPA")||String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("HSPA")|| String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("HSPAP")){
InfoMap.put("MobileType","3G");
}else if(String.valueOf(mobileInfo.getSubtypeName()).equalsIgnoreCase("LTE") ){
InfoMap.put("MobileType","4G");
}else{
InfoMap.put("MobileType",String.valueOf(mobileInfo.getSubtypeName()));
}
InfoMap.put("Mobile-Roaming",String.valueOf(mobileInfo.isRoaming()));
InfoMap.put("Mobile-SignalInfo",String.valueOf(mobileInfo.isRoaming()));
InfoMap.put("Mobile-State",String.valueOf(mobileInfo.getState()));
Log.e(TAG,"-----CONNECTION STATUS-----\n");
for (String keyval : InfoMap.keySet()){
Log.i(TAG,"Connection : "+keyval+" :"+InfoMap.get(keyval));
}
Map<String, String> wifiDetails = DisplayWifiState();
Log.e(TAG,"-----WIFI DETAILS-----\n");
for (String keywifival : wifiDetails.keySet()){
Log.i(TAG,"WIFI details : "+keywifival+" : "+wifiDetails.get(keywifival));
}
//Installed Apps :
PackageManager pm = context.getPackageManager();
List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.SIGNATURE_MATCH);
Log.e(TAG,"INSTALLED Apps size : "+apps.size());
installapp_map = new HashMap<String,String>();
Log.e(TAG,"-----INSTALLED APPS-----\n");
for (PackageInfo rInfo :apps) {
Log.i(TAG,"Installed Apps : "+rInfo.packageName+" : "+rInfo.applicationInfo.loadLabel(pm).toString());
installapp_map.put(rInfo.packageName, rInfo.applicationInfo.loadLabel(pm).toString());
}
runningAppProcessInfo=searchRunningAppProcesses();
healthModel.setRunningprocessInfo(new JSONObject(runningAppProcessInfo));
NetInfo netInfo = new NetInfo(context);
inetaddrinfo = netInfo.getIPAddress();
if(!(String.valueOf(wifiInfo.getState()).equalsIgnoreCase("connected"))){
if(inetaddrinfo !=null) {
for (String keyString : inetaddrinfo.keySet()) {
Log.e(TAG, "Internet : " + keyString + " :" + inetaddrinfo.get(keyString));
}
}else {
Log.e(TAG,"Internet : "+"NO");
}
}else
{
// for (String keyString : inetaddrinfo.keySet()) {
// Log.e(TAG, "Internet : " + keyString + " :" + inetaddrinfo.get(keyString));
// }
}
//Current Apps:
currnt_task_map = new HashMap<String, String>();
List<ActivityManager.RunningTaskInfo> infos = manager.getRunningTasks(Integer.MAX_VALUE);
PackageManager pack=context.getPackageManager();
Log.e(TAG,"-----CURRENT APP-----\n");
String currentApp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
String currentAppName="";
try {
currentAppName = (String) pack.getApplicationLabel(pack.getApplicationInfo(currentApp, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG,"Current App : "+currentApp+" : "+currentAppName);
currnt_task_map.put(currentApp,currentAppName);
}
}
}else {
for (ActivityManager.RunningTaskInfo info :infos) {
String packageName = info.topActivity.getPackageName();
String appName="";
try {
appName = (String) pack.getApplicationLabel(pack.getApplicationInfo(packageName,PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG,"Current App : "+packageName+" :"+appName );
currnt_task_map.put(packageName,appName);
}
}
//Recently used apps :
recent_task_map = new HashMap<String, String>();
Log.e(TAG,"-----RECENT APPS-----\n");
PackageManager recpack=context.getPackageManager();
List<ActivityManager.RecentTaskInfo> recentTasks = manager.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_WITH_EXCLUDED);
String Recentapp = "NULL";
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
if (mySortedMap != null && !mySortedMap.isEmpty()) {
Recentapp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
String RecentAppName = "";
try {
RecentAppName = (String) recpack.getApplicationLabel(recpack.getApplicationInfo(Recentapp, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG, "Recent Apps : " + Recentapp + " : " + RecentAppName);
recent_task_map.put(Recentapp, RecentAppName);
}
}
}
}else {
for (ActivityManager.RecentTaskInfo task : recentTasks) {
Intent baseIntent = task.baseIntent;
if (baseIntent != null) {
String text = baseIntent.getComponent().getPackageName();
String appName = "";
try {
appName = (String) pack.getApplicationLabel(pack.getApplicationInfo(text, PackageManager.GET_META_DATA));
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
Log.i(TAG, "Recent Apps : " + text + " :" + appName);
recent_task_map.put(text,(String) appName);
}else {
Log.i(TAG,"RecentTask :"+" No Recent task");
}
}
}
//Location info :
location_info = new HashMap<String,String>();
double Latitude=AppLockApplication.getInstance().getlocationprovider().getLocation().getLatitude();
double Longitude=AppLockApplication.getInstance().getlocationprovider().getLocation().getLongitude();
Log.e(TAG,"-----LOCATION-----");
location_info.put("Latitude",String.valueOf(Latitude));
location_info.put("Longitude",String.valueOf(Longitude));
for (String keyset : location_info.keySet()){
Log.i(TAG,"Location info : "+keyset+" : "+location_info.get(keyset));
}
if(siminfoMap !=null){
healthModel.setSiminfo(new JSONObject(siminfoMap));
}
healthModel.setWifideatils(new JSONObject(wifiDetails));
healthModel.setConectivityInfo(new JSONObject(InfoMap));
healthModel.setBatteryInfo(new JSONObject(batteryinfoMap));
healthModel.setMemoreyInfo(new JSONObject(memory_info));
healthModel.setInstallAppInfo(new JSONObject(installapp_map));
healthModel.setLocationinfo(new JSONObject(location_info));
healthModel.setInternalmemory(new JSONObject(internal_memory));
if (extrenal_memory !=null) {
healthModel.setExternalmemoryinfo(new JSONObject(extrenal_memory));
}
if(inetaddrinfo !=null){
healthModel.setinetaddress(new JSONObject(inetaddrinfo));
}
healthModel.setCurTaskInfo(new JSONObject(currnt_task_map));
healthModel.setRecentTaskInfo(new JSONObject(recent_task_map));
if(siminfoMap !=null){
healthinfo_Map.put("SIMINFORMATION",healthModel.getSiminfo());
}
healthinfo_Map.put("BATTERYINFO", healthModel.getBatteryInfo());
healthinfo_Map.put("WIFIDETAILS", healthModel.getConectivityInfo());
healthinfo_Map.put("WIFIINFO", healthModel.getWifideatils());
healthinfo_Map.put("MEMORYINFO", healthModel.getMemoreyInfo());
healthinfo_Map.put("INSTALLAPPINFO",healthModel.getInstallAppInfo());
healthinfo_Map.put("RUNNINGAPPINFO", healthModel.getRunningprocessInfo());
healthinfo_Map.put("CURRTASKINFO", healthModel.getCurTaskInfo());
healthinfo_Map.put("RECENTTASKINFO", healthModel.getRecentTaskInfo());
healthinfo_Map.put("INETADDRESS", healthModel.getinetaddress());
healthinfo_Map.put("LOCATION",healthModel.getLocationinfo());
healthinfo_Map.put("INTERNALMEMORY",healthModel.getInternalmemory());
healthinfo_Map.put("EXTERNALMEMORY",healthModel.getExternalmemoryinfo());
jsonObject=new JSONObject(healthinfo_Map);
healthinfo_Map=null;
healthModel=null;
siminfoMap=null;
wifiDetails=null;
InfoMap=null;
batteryinfoMap=null;
memory_info=null;
installapp_map=null;
location_info=null;
internal_memory=null;
extrenal_memory=null;
inetaddrinfo=null;
currnt_task_map=null;
recent_task_map=null;
jsonObject=null;
runningAppProcessInfo=null;
}
};
答案 0 :(得分:2)
使用运行1小时的AlarmManager启动广播接收器
public int setAlarm() {
Calendar Calendar_Object = Calendar.getInstance();
Intent myIntent = new Intent(Splash.this, mBatInfoReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long wkupTime = Calendar_Object.getTimeInMillis() + 36000;
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, wkupTime ,3600000, pendingIntent);
return 0;
}
检查here
答案 1 :(得分:2)
使用AlarmManager实现此目的 https://developer.android.com/training/scheduling/alarms.html
答案 2 :(得分:1)
您可以使用处理程序设置时间来调用接收器内部 服务。请尝试以下代码:
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
@Override
public void run() {
//you can call your broadcast receiver here
}
};
timer.schedule(hourlyTask, 01, 1000 * 1 * 60 * 60);