现在我有我的主要Activity,它执行以下操作:在创建时,它会收集有关手机和运行应用程序的数据。我还做了额外的计算并使用不同的数据类型来存储它们以绘制图形(例如我使用HashTable)。我还有一个处理程序,可以每分钟重新获取数据并更新图表和文本视图。
现在问题来了。我正在考虑创建一个服务(或IntentService?)来每分钟收集数据,然后将该数据发送到Activity,以便它可以更新图表等等。
1.对于这种方法谁应该使用处理程序,活动或服务?
2.如何让他们进行沟通,BroadCastReceiver会成为最佳解决方案吗?
3.如果是这样,我如何发送数据以及我可以发送哪种数据?例如,我使用aChartEngine绘制graps。基本上我创建一个GraphicalView来保存图表,然后将其添加到linearLayout。我可以从服务发送GraphicalView并将其添加到活动内的LinearLayout吗?
我可以将整个列表或哈希表从服务发送到主要活动吗?
我是Android开发的新手,我在这一点上陷入困境,一些提示和指南将帮助我很多。感谢
LE:收集服务内部的东西
public void getAppResources() throws IOException{
AndroidPowerCollector myCollector = new AndroidPowerCollector();
//////Running apps///////
ActivityManager actvityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> myApps = actvityManager.getRunningAppProcesses();
resourceTab.removeAllViews();
if(cpu_Values.isEmpty() == false)
cpu_Values.clear();
if(gps_Values.isEmpty() == false)
gps_Values.clear();
if(wifi_Values.isEmpty() == false)
wifi_Values.clear();
double maxWIFI=0;
double maxGPS=0;
double maxCPU=0;
highestDrainPackageCPU=null;
highestDrainPackageGPS=null;
highestDrainPackageWIFI=null;
//////////////////////////////
//Open file to save a log
FileWriter file = new FileWriter(new File(log_path,"AppResources.txt"),true);
//Get current time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss ");
String date = sdf.format(c.getTime());
file.write("TimeStamp:\t"+date+"\n");
View delimitator;
for(int i=0;i<myApps.size();i++){
//Get App name or Package name
PackageManager pm = this.getPackageManager();
String name = null;
try {
name = (String) pm.getApplicationLabel(pm.getApplicationInfo((myApps.get(i)).processName, PackageManager.GET_META_DATA));
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(name == null)
name=myApps.get(i).processName;
TextView [] infoApp = new TextView[7];
delimitator = new View(this);
delimitator.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,1));
delimitator.setBackgroundColor(Color.parseColor("#50FFFFFF"));
//////Setup textview//////////
for(int j=0;j<7;j++){
infoApp[j] = new TextView(this);
infoApp[j].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
infoApp[j].setTextColor(Color.parseColor("#FFFFFF"));
}
//////Collect data/////
PowerEvent current=myCollector.getPowerEvent(myApps.get(i).processName);
infoApp[0].setText("App:\t"+name+"\nCPU Time\t"+String.format("%d",current.getCpuTime())+"ms");
infoApp[1].setText("CPU Energy:\t"+String.format("%.2f",current.getCpuEnergy())+"mJ");
infoApp[2].setText("GPS Time:\t"+String.format("%d",current.getGpsTime())+"ms");
infoApp[3].setText("GPS Energy:\t"+String.format("%.2f",current.getGpsEnergy())+"mJ");
infoApp[4].setText("Sent data WiFi:\t"+String.format("%d",TrafficStats.getUidTxBytes(myApps.get(i).uid))+"bytes");
infoApp[5].setText("Recv data WiFi:\t"+String.format("%d",TrafficStats.getUidRxBytes(myApps.get(i).uid))+"bytes");
if(current.getCpuEnergy() > 0){
//Add CPU usage for PIE CHART
BasicNameValuePair entry = new BasicNameValuePair(name, String.valueOf(Math.round(current.getCpuEnergy()*100.0)/100.0 ));
cpu_Values.add(entry);
//Add CPU usage for LINE CHART
String packet=myApps.get(i).processName;
if(tableCPU.containsKey(packet) == true){
//Get existing values
List<BasicNameValuePair> newList = new ArrayList<BasicNameValuePair>();
newList = tableCPU.get(packet);
//Add current value
newList.add(new BasicNameValuePair(String.valueOf(realTime),String.valueOf(Math.round(current.getCpuEnergy()*100.0)/100.0)));
//Replace value in hashtable
tableCPU.put(packet,newList);
}
else{
List<BasicNameValuePair> newList = new ArrayList<BasicNameValuePair>();
//Add current value
newList.add(new BasicNameValuePair(String.valueOf(realTime),String.valueOf(Math.round(current.getCpuEnergy()*100.0)/100.0)));
tableCPU.put(packet, newList);
}
//Get highest draining package
if(current.getCpuEnergy() > maxCPU){
maxCPU=current.getCpuEnergy();
highestDrainPackageCPU=packet;
}
}
if(current.getGpsEnergy() > 0){
//Add GPS usage for PIE CHART
BasicNameValuePair entry = new BasicNameValuePair(name, String.valueOf(Math.round(current.getGpsEnergy()*100.0)/100.0 ));
gps_Values.add(entry);
//Add GPS usage for LINE CHART
String packet=myApps.get(i).processName;
if(tableGPS.containsKey(packet) == true){
//Get existing values
List<BasicNameValuePair> newList = new ArrayList<BasicNameValuePair>();
newList = tableGPS.get(packet);
//Add current value
newList.add(new BasicNameValuePair(String.valueOf(realTime),String.valueOf(Math.round(current.getGpsEnergy()*100.0)/100.0)));
//Replace value in hashtable
tableGPS.put(packet,newList);
}
else{
List<BasicNameValuePair> newList = new ArrayList<BasicNameValuePair>();
//Add current value
newList.add(new BasicNameValuePair(String.valueOf(realTime),String.valueOf(Math.round(current.getGpsEnergy()*100.0)/100.0)));
tableGPS.put(packet, newList);
}
//Get package with highest GPS drain
if(current.getGpsEnergy() > maxGPS){
maxGPS=current.getGpsEnergy();
highestDrainPackageGPS=packet;
}
}
//transfer of 50KB over wifi =~ 920mJ
double averageWifiEnergy=TrafficStats.getUidTxBytes(myApps.get(i).uid)+TrafficStats.getUidRxBytes(myApps.get(i).uid)/51200 * 920;
infoApp[6].setText("WiFi Energy:\t"+String.format("%f",averageWifiEnergy)+"mJ");
if(averageWifiEnergy > 0){
//Add WIFI usage for PIE CHART
BasicNameValuePair entry = new BasicNameValuePair(name, String.valueOf(averageWifiEnergy));
wifi_Values.add(entry);
//Add wifi usage for LINE CHART
String packet=myApps.get(i).processName;
if(tableWIFI.containsKey(packet) == true){
//Get existing values
List<BasicNameValuePair> newList = new ArrayList<BasicNameValuePair>();
newList = tableWIFI.get(packet);
//Add current value
newList.add(new BasicNameValuePair(String.valueOf(realTime),String.valueOf(averageWifiEnergy)));
//Replace value in hashtable
tableWIFI.put(packet,newList);
}
else{
List<BasicNameValuePair> newList = new ArrayList<BasicNameValuePair>();
//Add current value
newList.add(new BasicNameValuePair(String.valueOf(realTime),String.valueOf(averageWifiEnergy)));
tableWIFI.put(packet, newList);
}
//Get highest Wifi draining package
if(averageWifiEnergy > maxWIFI){
maxWIFI=averageWifiEnergy;
highestDrainPackageWIFI=packet;
}
}
//add textviews to a linear layout
for(int j=0;j<7;j++){
resourceTab.addView(infoApp[j]);
}
resourceTab.addView(delimitator);
//Write the log
Log.d("LOGS","Write resource logs");
for(int j=0;j<7;j++)
file.write(infoApp[j].getText()+"\n");
}
file.close();
realTime+=60;
}
答案 0 :(得分:2)
服务没有提供任何用户界面,因此您必须将它们绑定/或使用广播与activites.which反过来在相互通信后显示UI中的值。从活动启动服务。< / p>
serviceIntent = new Intent(this, Music_service.class);
serviceIntent.putParcelableArrayListExtra("sentAudioLink", songdetails);//here "sentAudioLink //is the key which needs to be same in the service ,so that you can send
serviceIntent.putExtra("postion_service", position);
startService(serviceIntent);
现在服务已经开始......
服务内部读取之前传递的数据
songdetails = intent.getParcelableArrayListExtra("sentAudioLink");
position = intent.getIntExtra("postion_service", 0);
//note "sentAudioLink",its the key value,or the identifier which remains the same on sending and receiving
但是使用上述方法发送数据只会在服务启动期间发送一次值,但在您的情况下,您会经常想要发送和接收数据....
所以在服务内部,无论你计算什么,都需要经常发送到活动,以便UI可以更新,其他事情可以完成,在这种情况下你也想使用广播
public static final String BROADCAST_BUFFER = "source.justanothermusicplayer.broadcastbuffer";
bufferIntent = new Intent(BROADCAST_BUFFER);;//You can put any value into Broadcast_Buffer ,it is just a unique identifier for each broadcast
and then now that you hav initialized the intent its time to put values into it and send them using a broadcast
///
bufferIntent.putExtra("buffering", "2");
sendBroadcast(bufferIntent);
将上面两行放在一个方法中,每当发生更改时调用该方法,例如单击按钮或时间更改时,例如
Ontimerchanged(){
bufferIntent.putExtra("buffering", thevalueoftimer);//buffering is the key again...
sendBroadcast(bufferIntent);
}
现在进入活动内部再次注册活动内的广播
registerReceiver(broadcastReceiver, new IntentFilter(
Music_service.BROADCAST_BUFFER));//remeber the "BROADCAST_BUFFER" we created in the service??this is the same ...if you use BROADCAST_BUFFER2 or something like that or any other thing,it won't work.
现在创建此方法
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent serviceIntent) {
Anymethod(serviceIntent);//serviceIntent has the values that are being passed...in your case value of timer etc.recieve the values in the method
//TODO
}
};
//
AnyMethod(){
//receiving the values here......
String valueoftimer = serviceIntent.getStringExtra("buffering");//again the key needs to be same
//now that you have received the values ,you can set them up in a textview....
}
如果我的回答有帮助,请接受