EmmageeService.java 20.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2012-2013 NetEase, Inc. and other contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
K
kevinkong 已提交
17 18
package com.netease.qa.emmagee.service;

H
hzhuangqingbin 已提交
19
import java.io.BufferedReader;
K
kevinkong 已提交
20 21
import java.io.BufferedWriter;
import java.io.File;
A
andrewleo2013 已提交
22
import java.io.FileInputStream;
A
commit  
andrewleo 已提交
23
import java.io.FileNotFoundException;
K
kevinkong 已提交
24
import java.io.FileOutputStream;
H
hzhuangqingbin 已提交
25
import java.io.FileReader;
K
kevinkong 已提交
26
import java.io.IOException;
H
hzhuangqingbin 已提交
27
import java.io.InputStreamReader;
K
kevinkong 已提交
28 29 30 31 32
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
A
andrewleo2013 已提交
33
import java.util.Properties;
K
kevinkong 已提交
34 35

import android.app.Activity;
fix bug  
已提交
36
import android.app.PendingIntent;
K
kevinkong 已提交
37
import android.app.Service;
A
commit  
andrewleo 已提交
38
import android.content.BroadcastReceiver;
K
kevinkong 已提交
39 40
import android.content.Context;
import android.content.Intent;
A
commit  
andrewleo 已提交
41
import android.content.IntentFilter;
K
kevinkong 已提交
42 43
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
A
commit  
andrewleo 已提交
44
import android.os.BatteryManager;
A
andrewleo2013 已提交
45
import android.os.Build;
K
kevinkong 已提交
46 47
import android.os.Handler;
import android.os.IBinder;
fix bug  
已提交
48
import android.support.v4.app.NotificationCompat;
K
kevinkong 已提交
49 50 51 52 53 54 55 56 57 58 59 60
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

A
commit  
andrewleo 已提交
61
import com.netease.qa.emmagee.R;
fix bug  
已提交
62
import com.netease.qa.emmagee.activity.MainPageActivity;
K
kevinkong 已提交
63
import com.netease.qa.emmagee.utils.CpuInfo;
A
commit  
andrewleo 已提交
64
import com.netease.qa.emmagee.utils.CurrentInfo;
A
andrewleo2013 已提交
65 66
import com.netease.qa.emmagee.utils.EncryptData;
import com.netease.qa.emmagee.utils.MailSender;
K
kevinkong 已提交
67 68 69
import com.netease.qa.emmagee.utils.MemoryInfo;
import com.netease.qa.emmagee.utils.MyApplication;

70 71
/**
 * Service running in background
A
andrewleo2013 已提交
72
 * 
A
andrewleo 已提交
73
 * @author andrewleo
74
 */
K
kevinkong 已提交
75
public class EmmageeService extends Service {
76

77
	private final static String LOG_TAG = "Emmagee-" + EmmageeService.class.getSimpleName();
K
kevinkong 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90

	private WindowManager windowManager = null;
	private WindowManager.LayoutParams wmParams = null;
	private View viFloatingWindow;
	private float mTouchStartX;
	private float mTouchStartY;
	private float startX;
	private float startY;
	private float x;
	private float y;
	private TextView txtTotalMem;
	private TextView txtUnusedMem;
	private TextView txtTraffic;
91
	private Button btnStop;
K
kevinkong 已提交
92 93 94 95 96 97 98 99
	private Button btnWifi;
	private int delaytime;
	private DecimalFormat fomart;
	private MemoryInfo memoryInfo;
	private WifiManager wifiManager;
	private Handler handler = new Handler();
	private CpuInfo cpuInfo;
	private String time;
100
	private boolean isFloating;
101
	private String processName, packageName, settingTempFile, startActivity;
102
	private int pid, uid;
103
	private boolean isServiceStop = false;
A
andrewleo2013 已提交
104 105 106
	private String sender, password, recipients, smtp;
	private String[] receivers;
	private EncryptData des;
K
kevinkong 已提交
107 108 109 110 111

	public static BufferedWriter bw;
	public static FileOutputStream out;
	public static OutputStreamWriter osw;
	public static String resultFilePath;
112
	public static boolean isStop = false;
K
kevinkong 已提交
113

A
commit  
andrewleo 已提交
114 115 116 117
	private String totalBatt;
	private String temperature;
	private String voltage;
	private CurrentInfo currentInfo;
118
	private BatteryInfoBroadcastReceiver batteryBroadcast = null;
A
commit  
andrewleo 已提交
119

H
hzhuangqingbin 已提交
120 121 122
	// get start time
	private static final int MAX_START_TIME_COUNT = 5;
	private static final String START_TIME = "#startTime";
H
hzhuangqingbin 已提交
123 124 125
	private int getStartTimeCount = 0;
	private boolean isGetStartTime = true;
	private String startTime = "";
126
	private static final String SERVICE_ACTION = "com.netease.action.emmageeService";
H
hzhuangqingbin 已提交
127

K
kevinkong 已提交
128 129 130 131
	@Override
	public void onCreate() {
		Log.i(LOG_TAG, "onCreate");
		super.onCreate();
132 133
		isServiceStop = false;
		isStop = false;
K
kevinkong 已提交
134 135 136 137
		memoryInfo = new MemoryInfo();
		fomart = new DecimalFormat();
		fomart.setMaximumFractionDigits(2);
		fomart.setMinimumFractionDigits(0);
A
andrewleo2013 已提交
138
		des = new EncryptData("emmagee");
A
commit  
andrewleo 已提交
139
		currentInfo = new CurrentInfo();
140 141
		batteryBroadcast = new BatteryInfoBroadcastReceiver();
		registerReceiver(batteryBroadcast, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
A
commit  
andrewleo 已提交
142 143 144 145 146
	}

	/**
	 * 电池信息监控监听器
	 * 
147
	 * @author andrewleo
A
commit  
andrewleo 已提交
148 149 150 151 152 153 154 155 156 157 158
	 * 
	 */
	public class BatteryInfoBroadcastReceiver extends BroadcastReceiver {

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

			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
				int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

				int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
K
kevinkong 已提交
159
				totalBatt = String.valueOf(level * 100 / scale);
A
commit  
andrewleo 已提交
160

161
				voltage = String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1) * 1.0 / 1000);
A
commit  
andrewleo 已提交
162

163
				temperature = String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1) * 1.0 / 10);
A
commit  
andrewleo 已提交
164 165 166 167
			}

		}

K
kevinkong 已提交
168 169 170 171 172
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(LOG_TAG, "onStart");
173 174 175
		PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0, new Intent(this, MainPageActivity.class), 0);
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
		builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon).setWhen(System.currentTimeMillis()).setAutoCancel(true)
fix bug  
已提交
176 177
				.setContentTitle("Emmagee");
		startForeground(startId, builder.build());
178

K
kevinkong 已提交
179 180 181 182 183
		pid = intent.getExtras().getInt("pid");
		uid = intent.getExtras().getInt("uid");
		processName = intent.getExtras().getString("processName");
		packageName = intent.getExtras().getString("packageName");
		settingTempFile = intent.getExtras().getString("settingTempFile");
184
		startActivity = intent.getExtras().getString("startActivity");
185 186

		cpuInfo = new CpuInfo(getBaseContext(), pid, Integer.toString(uid));
K
kevinkong 已提交
187 188 189
		readSettingInfo(intent);
		delaytime = Integer.parseInt(time) * 1000;
		if (isFloating) {
190 191 192
			viFloatingWindow = LayoutInflater.from(this).inflate(R.layout.floating, null);
			txtUnusedMem = (TextView) viFloatingWindow.findViewById(R.id.memunused);
			txtTotalMem = (TextView) viFloatingWindow.findViewById(R.id.memtotal);
K
kevinkong 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205
			txtTraffic = (TextView) viFloatingWindow.findViewById(R.id.traffic);
			btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);

			wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
			if (wifiManager.isWifiEnabled()) {
				btnWifi.setText(R.string.closewifi);
			} else {
				btnWifi.setText(R.string.openwifi);
			}
			txtUnusedMem.setText("计算中,请稍后...");
			txtUnusedMem.setTextColor(android.graphics.Color.RED);
			txtTotalMem.setTextColor(android.graphics.Color.RED);
			txtTraffic.setTextColor(android.graphics.Color.RED);
206 207
			btnStop = (Button) viFloatingWindow.findViewById(R.id.stop);
			btnStop.setOnClickListener(new OnClickListener() {
A
andrewleo 已提交
208 209
				@Override
				public void onClick(View v) {
210 211
					Intent intent = new Intent();
					intent.putExtra("isServiceStop", true);
212
					intent.setAction(SERVICE_ACTION);
213
					sendBroadcast(intent);
A
andrewleo 已提交
214 215 216
					stopSelf();
				}
			});
K
kevinkong 已提交
217 218 219
			createFloatingWindow();
		}
		createResultCsv();
220
		handler.postDelayed(task, 1000);
K
kevinkong 已提交
221 222 223
	}

	/**
A
andrewleo2013 已提交
224
	 * read configuration file.
K
kevinkong 已提交
225 226 227 228 229
	 * 
	 * @throws IOException
	 */
	private void readSettingInfo(Intent intent) {
		try {
A
andrewleo2013 已提交
230 231 232
			Properties properties = new Properties();
			properties.load(new FileInputStream(settingTempFile));
			String interval = properties.getProperty("interval").trim();
233
			isFloating = "true".equals(properties.getProperty("isfloat").trim()) ? true : false;
A
andrewleo2013 已提交
234 235 236 237 238 239 240
			sender = properties.getProperty("sender").trim();
			password = properties.getProperty("password").trim();
			recipients = properties.getProperty("recipients").trim();
			time = "".equals(interval) ? "5" : interval;
			recipients = properties.getProperty("recipients");
			receivers = recipients.split("\\s+");
			smtp = properties.getProperty("smtp");
K
kevinkong 已提交
241 242 243 244
		} catch (IOException e) {
			time = "5";
			isFloating = true;
			Log.e(LOG_TAG, e.getMessage());
A
andrewleo2013 已提交
245
		}
K
kevinkong 已提交
246 247 248
	}

	/**
A
andrewleo2013 已提交
249
	 * write the test result to csv format report.
K
kevinkong 已提交
250 251 252 253
	 */
	private void createResultCsv() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
A
andrewleo2013 已提交
254 255
		String mDateTime;
		if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk")))
256
			mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
A
andrewleo2013 已提交
257 258
		else
			mDateTime = formatter.format(cal.getTime().getTime());
259
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
260 261 262
			//在4.0以下的低版本上/sdcard连接至/mnt/sdcard,而4.0以上版本则连接至/storage/sdcard0,所以有外接sdcard,/sdcard路径一定存在
			resultFilePath = "/sdcard"+ File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";	
			//resultFilePath = android.os.Environment.getExternalStorageDirectory() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
K
kevinkong 已提交
263
		} else {
264
			resultFilePath = getBaseContext().getFilesDir().getPath() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
K
kevinkong 已提交
265 266 267 268 269
		}
		try {
			File resultFile = new File(resultFilePath);
			resultFile.createNewFile();
			out = new FileOutputStream(resultFile);
H
hzhuangqingbin 已提交
270
			osw = new OutputStreamWriter(out, "UTF-8");
K
kevinkong 已提交
271 272 273
			bw = new BufferedWriter(osw);
			long totalMemorySize = memoryInfo.getTotalMemory();
			String totalMemory = fomart.format((double) totalMemorySize / 1024);
274 275 276 277 278 279
			String multiCpuTitle = "";
			// titles of multiple cpu cores 
			ArrayList<String> cpuList = cpuInfo.getCpuList();
			for(int i =0 ; i < cpuList.size(); i++){
				multiCpuTitle += ","+cpuList.get(i)+"总使用率(%)";
			}
280 281
			bw.write("指定应用的CPU内存监控情况\r\n" + "应用包名:," + packageName + "\r\n" + "应用名称: ," + processName + "\r\n" + "应用PID: ," + pid + "\r\n"
					+ "机器内存大小(MB):," + totalMemory + "MB\r\n" + "机器CPU型号:," + cpuInfo.getCpuName() + "\r\n" + "机器android系统版本:,"
282
					+ memoryInfo.getSDKVersion() + "\r\n" + "手机型号:," + memoryInfo.getPhoneType() + "\r\n" + "UID:," + uid + "\r\n" + START_TIME);
283 284
			bw.write("时间" + "," + "应用占用内存PSS(MB)" + "," + "应用占用内存比(%)" + "," + " 机器剩余内存(MB)" + "," + "应用占用CPU率(%)" + "," + "CPU总使用率(%)"
					+ multiCpuTitle +"," + "流量(KB)" + "," + "电量(%)" + "," + "电流(mA)" + "," + "温度(C)" + "," + "电压(V)" + "\r\n");
K
kevinkong 已提交
285 286 287 288 289 290
		} catch (IOException e) {
			Log.e(LOG_TAG, e.getMessage());
		}
	}

	/**
A
andrewleo2013 已提交
291
	 * create a floating window to show real-time data.
K
kevinkong 已提交
292 293
	 */
	private void createFloatingWindow() {
294
		SharedPreferences shared = getSharedPreferences("float_flag", Activity.MODE_PRIVATE);
K
kevinkong 已提交
295 296 297
		SharedPreferences.Editor editor = shared.edit();
		editor.putInt("float", 1);
		editor.commit();
298
		windowManager = (WindowManager) getApplicationContext().getSystemService("window");
K
kevinkong 已提交
299 300 301
		wmParams = ((MyApplication) getApplication()).getMywmParams();
		wmParams.type = 2002;
		wmParams.flags |= 8;
302
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
K
kevinkong 已提交
303 304 305 306 307 308 309 310 311
		wmParams.x = 0;
		wmParams.y = 0;
		wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.format = 1;
		windowManager.addView(viFloatingWindow, wmParams);
		viFloatingWindow.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				x = event.getRawX();
312
				y = event.getRawY() - 25;
K
kevinkong 已提交
313 314 315 316 317 318 319 320 321 322 323 324
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startX = x;
					startY = y;
					mTouchStartX = event.getX();
					mTouchStartY = event.getY();
					break;
				case MotionEvent.ACTION_MOVE:
					updateViewPosition();
					break;
				case MotionEvent.ACTION_UP:
					updateViewPosition();
325
					// showImg();
K
kevinkong 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338
					mTouchStartX = mTouchStartY = 0;
					break;
				}
				return true;
			}
		});

		btnWifi.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					btnWifi = (Button) viFloatingWindow.findViewById(R.id.wifi);
					String buttonText = (String) btnWifi.getText();
339
					String wifiText = getResources().getString(R.string.openwifi);
K
kevinkong 已提交
340 341 342 343 344 345 346 347
					if (buttonText.equals(wifiText)) {
						wifiManager.setWifiEnabled(true);
						btnWifi.setText(R.string.closewifi);
					} else {
						wifiManager.setWifiEnabled(false);
						btnWifi.setText(R.string.openwifi);
					}
				} catch (Exception e) {
348
					Toast.makeText(viFloatingWindow.getContext(), "操作wifi失败", Toast.LENGTH_LONG).show();
K
kevinkong 已提交
349 350 351 352 353 354
					Log.e(LOG_TAG, e.toString());
				}
			}
		});
	}

355 356 357 358 359 360 361 362 363 364 365
	// /**
	// * show the image.
	// */
	// private void showImg() {
	// if (Math.abs(x - startX) < 1.5 && Math.abs(y - startY) < 1.5 &&
	// !btnStop.isShown()) {
	// btnStop.setVisibility(View.VISIBLE);
	// } else if (btnStop.isShown()) {
	// btnStop.setVisibility(View.GONE);
	// }
	// }
K
kevinkong 已提交
366 367

	private Runnable task = new Runnable() {
368

K
kevinkong 已提交
369
		public void run() {
370 371 372
			if (!isServiceStop) {
				dataRefresh();
				handler.postDelayed(this, delaytime);
H
hzhuangqingbin 已提交
373
				if (isFloating) {
374
					windowManager.updateViewLayout(viFloatingWindow, wmParams);
H
hzhuangqingbin 已提交
375
				}
H
hzhuangqingbin 已提交
376
				// get app start time from logcat on every task running
H
hzhuangqingbin 已提交
377
				getStartTimeFromLogcat();
378 379 380
			} else {
				Intent intent = new Intent();
				intent.putExtra("isServiceStop", true);
381
				intent.setAction(SERVICE_ACTION);
382 383 384
				sendBroadcast(intent);
				stopSelf();
			}
K
kevinkong 已提交
385 386 387
		}
	};

H
hzhuangqingbin 已提交
388
	/**
H
hzhuangqingbin 已提交
389
	 * Try to get start time from logcat.
H
hzhuangqingbin 已提交
390 391
	 */
	private void getStartTimeFromLogcat() {
H
hzhuangqingbin 已提交
392 393 394 395 396 397 398 399
		if (!isGetStartTime || getStartTimeCount >= MAX_START_TIME_COUNT) {
			return;
		}
		try {
			// filter logcat by Tag:ActivityManager and Level:Info
			String logcatCommand = "logcat -v time -d ActivityManager:I *:S";
			Process process = Runtime.getRuntime().exec(logcatCommand);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
400
			StringBuilder strBuilder = new StringBuilder();
H
hzhuangqingbin 已提交
401 402 403
			String line = "";

			while ((line = bufferedReader.readLine()) != null) {
404 405 406 407 408
				strBuilder.append(line);
				strBuilder.append("\r\n");
				String regex = ".*Displayed.*" + startActivity + ".*\\+(.*)ms.*";
				if (line.matches(regex)) {
					Log.w("my logs", line);
409 410 411
					if (line.contains("total")) {
						line = line.substring(0, line.indexOf("total"));
					}
H
hzhuangqingbin 已提交
412 413 414
					startTime = line.substring(line.lastIndexOf("+") + 1, line.lastIndexOf("ms") + 2);
					Toast.makeText(EmmageeService.this, "启动时间:" + startTime, Toast.LENGTH_LONG).show();
					isGetStartTime = false;
415
					break;
H
hzhuangqingbin 已提交
416 417
				}
			}
H
hzhuangqingbin 已提交
418 419 420
			getStartTimeCount++;
		} catch (IOException e) {
			Log.d(LOG_TAG, e.getMessage());
H
hzhuangqingbin 已提交
421 422 423
		}
	}

K
kevinkong 已提交
424
	/**
A
andrewleo2013 已提交
425
	 * refresh the performance data showing in floating window.
A
andrewleo2013 已提交
426
	 * 
K
kevinkong 已提交
427
	 * @throws FileNotFoundException
A
andrewleo2013 已提交
428
	 * 
K
kevinkong 已提交
429 430 431
	 * @throws IOException
	 */
	private void dataRefresh() {
432
		int pidMemory = memoryInfo.getPidMemorySize(pid, getBaseContext());
K
kevinkong 已提交
433 434 435
		long freeMemory = memoryInfo.getFreeMemorySize(getBaseContext());
		String freeMemoryKb = fomart.format((double) freeMemory / 1024);
		String processMemory = fomart.format((double) pidMemory / 1024);
436
		String currentBatt = String.valueOf(currentInfo.getCurrentValue());
437 438 439 440 441 442 443 444
		// 异常数据过滤
		try {
			if (Math.abs(Double.parseDouble(currentBatt)) >= 500) {
				currentBatt = "N/A";
			}
		} catch (Exception e) {
			currentBatt = "N/A";
		}
445
		ArrayList<String> processInfo = cpuInfo.getCpuRatioInfo(totalBatt, currentBatt, temperature, voltage);
K
kevinkong 已提交
446 447 448 449 450 451 452 453 454 455 456
		if (isFloating) {
			String processCpuRatio = "0";
			String totalCpuRatio = "0";
			String trafficSize = "0";
			int tempTraffic = 0;
			double trafficMb = 0;
			boolean isMb = false;
			if (!processInfo.isEmpty()) {
				processCpuRatio = processInfo.get(0);
				totalCpuRatio = processInfo.get(1);
				trafficSize = processInfo.get(2);
A
andrewleo 已提交
457
				if (!("".equals(trafficSize)) && !("-1".equals(trafficSize))) {
K
kevinkong 已提交
458 459 460 461 462 463
					tempTraffic = Integer.parseInt(trafficSize);
					if (tempTraffic > 1024) {
						isMb = true;
						trafficMb = (double) tempTraffic / 1024;
					}
				}
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
				// 如果cpu使用率存在且都不小于0,则输出
				if (processCpuRatio != null && totalCpuRatio != null) {
					txtUnusedMem.setText("应用/剩余内存:" + processMemory + "/" + freeMemoryKb + "MB");
					txtTotalMem.setText("应用/总体CPU:" + processCpuRatio + "%/" + totalCpuRatio + "%");
					String batt = "电流:" + currentBatt;
					if ("-1".equals(trafficSize)) {
						txtTraffic.setText(batt + ",流量:N/A");
					} else if (isMb)
						txtTraffic.setText(batt + ",流量:" + fomart.format(trafficMb) + "MB");
					else
						txtTraffic.setText(batt + ",流量:" + trafficSize + "KB");
				}
				// 当内存为0切cpu使用率为0时则是被测应用退出
				if ("0".equals(processMemory) && "0.00".equals(processCpuRatio)) {
					closeOpenedStream();
					isServiceStop = true;
					return;
				}
K
kevinkong 已提交
482
			}
483

K
kevinkong 已提交
484 485 486 487
		}
	}

	/**
A
andrewleo2013 已提交
488
	 * update the position of floating window.
K
kevinkong 已提交
489 490 491 492 493 494 495 496
	 */
	private void updateViewPosition() {
		wmParams.x = (int) (x - mTouchStartX);
		wmParams.y = (int) (y - mTouchStartY);
		windowManager.updateViewLayout(viFloatingWindow, wmParams);
	}

	/**
A
andrewleo2013 已提交
497
	 * close all opened stream.
K
kevinkong 已提交
498 499 500
	 */
	public static void closeOpenedStream() {
		try {
A
andrewleo 已提交
501 502
			if (bw != null) {
				bw.write("注释:已知部分不支持的机型可在此查阅:https://github.com/NetEase/Emmagee/wiki/Some-devices-are-not-supported \r\n");
503 504
				bw.write("电流:小于0是放电大于0是充电\r\n启动时间:为空是应用已启动或者未搜集到启动时间\r\n");
				bw.write("N/A表示不支持或者数据异常\r\n");
K
kevinkong 已提交
505
				bw.close();
A
andrewleo 已提交
506
			}
K
kevinkong 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
			if (osw != null)
				osw.close();
			if (out != null)
				out.close();
		} catch (Exception e) {
			Log.d(LOG_TAG, e.getMessage());
		}
	}

	@Override
	public void onDestroy() {
		Log.i(LOG_TAG, "onDestroy");
		if (windowManager != null)
			windowManager.removeView(viFloatingWindow);
		handler.removeCallbacks(task);
		closeOpenedStream();
H
hzhuangqingbin 已提交
523
		// replace the start time in file
524 525 526 527 528
		if (!"".equals(startTime)) {
			replaceFileString(resultFilePath, START_TIME, "启动时间:" + startTime + "\r\n");
		} else {
			replaceFileString(resultFilePath, START_TIME, "");
		}
529
		isStop = true;
530
		unregisterReceiver(batteryBroadcast);
A
andrewleo2013 已提交
531 532
		boolean isSendSuccessfully = false;
		try {
533
			isSendSuccessfully = MailSender.sendTextMail(sender, des.decrypt(password), smtp, "Emmagee Performance Test Report", "see attachment",
A
andrewleo2013 已提交
534 535 536 537 538
					resultFilePath, receivers);
		} catch (Exception e) {
			isSendSuccessfully = false;
		}
		if (isSendSuccessfully) {
539
			Toast.makeText(this, "测试结果报表已发送至邮箱:" + recipients, Toast.LENGTH_LONG).show();
A
andrewleo2013 已提交
540
		} else {
541
			Toast.makeText(this, "测试结果未成功发送至邮箱,结果保存在:" + EmmageeService.resultFilePath, Toast.LENGTH_LONG).show();
A
andrewleo2013 已提交
542
		}
543
		super.onDestroy();
fix bug  
已提交
544
		stopForeground(true);
K
kevinkong 已提交
545 546
	}

H
hzhuangqingbin 已提交
547
	/**
548 549 550
	 * Replaces all matches for replaceType within this replaceString in file on
	 * the filePath
	 * 
H
hzhuangqingbin 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
	 * @param filePath
	 * @param replaceType
	 * @param replaceString
	 */
	private void replaceFileString(String filePath, String replaceType, String replaceString) {
		try {
			File file = new File(filePath);
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line = "", oldtext = "";
			while ((line = reader.readLine()) != null) {
				oldtext += line + "\r\n";
			}
			reader.close();
			// replace a word in a file
			String newtext = oldtext.replaceAll(replaceType, replaceString);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
			writer.write(newtext);
			writer.close();
		} catch (IOException e) {
			Log.d(LOG_TAG, e.getMessage());
		}
	}

K
kevinkong 已提交
574 575 576 577
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
578
}