提交 d323b376 编写于 作者: A andrewleo

Added: support service alone & switch csv encoding to GBK

上级 2d2a44f9
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.netease.qa.emmagee"
android:versionCode="31"
android:versionName="2.2" >
package="com.netease.performancetestservice"
android:versionCode="32"
android:versionName="2.3" >
<uses-sdk android:minSdkVersion="8" />
......@@ -31,7 +31,8 @@
<activity android:name=".activity.MailSettingsActivity"
android:screenOrientation="portrait"/>
<service android:name="com.netease.qa.emmagee.service.EmmageeService"/>
<service android:name="com.netease.performancetestservice.MainService"
android:exported="true"/>
</application>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
......
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.service;
package com.netease.performancetestservice;
import java.io.BufferedReader;
import java.io.BufferedWriter;
......@@ -30,6 +30,7 @@ import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
......@@ -59,27 +60,26 @@ import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.netease.qa.emmagee.R;
import com.netease.qa.emmagee.activity.MainPageActivity;
import com.netease.qa.emmagee.utils.Constants;
import com.netease.qa.emmagee.utils.CpuInfo;
import com.netease.qa.emmagee.utils.CurrentInfo;
import com.netease.qa.emmagee.utils.EncryptData;
import com.netease.qa.emmagee.utils.MailSender;
import com.netease.qa.emmagee.utils.MemoryInfo;
import com.netease.qa.emmagee.utils.MyApplication;
import com.netease.qa.emmagee.utils.ProcessInfo;
import com.netease.qa.emmagee.utils.Programe;
import com.netease.qa.emmagee.utils.Settings;
import com.netease.performancetestservice.R;
import com.netease.performancetestservice.utils.Constants;
import com.netease.performancetestservice.utils.CpuInfo;
import com.netease.performancetestservice.utils.CurrentInfo;
import com.netease.performancetestservice.utils.EncryptData;
import com.netease.performancetestservice.utils.MailSender;
import com.netease.performancetestservice.utils.MemoryInfo;
import com.netease.performancetestservice.utils.MyApplication;
import com.netease.performancetestservice.utils.ProcessInfo;
import com.netease.performancetestservice.utils.Programe;
import com.netease.performancetestservice.utils.Settings;
/**
* Service running in background
*
* @author andrewleo
*/
public class EmmageeService extends Service {
public class MainService extends Service {
private final static String LOG_TAG = "Emmagee-" + EmmageeService.class.getSimpleName();
private final static String LOG_TAG = "Emmagee-" + MainService.class.getSimpleName();
private static final String BLANK_STRING = "";
......@@ -132,7 +132,9 @@ public class EmmageeService extends Service {
private String startTime = "";
public static final String SERVICE_ACTION = "com.netease.action.emmageeService";
private static final String BATTERY_CHANGED = "android.intent.action.BATTERY_CHANGED";
private static final String PERF_MONITOR_DIR = "/sdcard/grape";
private static final String PERF_MONITOR_FILE = PERF_MONITOR_DIR+"/PerformanceMonitor.csv";
@Override
public void onCreate() {
Log.i(LOG_TAG, "service onCreate");
......@@ -174,22 +176,48 @@ public class EmmageeService extends Service {
}
}
/**
* wait for test application started.
*
* @param packageName
* package name of test application
*/
public void waitForAppStart(String packageName,Context context) {
Log.d(LOG_TAG, "wait for app start");
boolean isProcessStarted = false;
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < startTime + Constants.WAIT_START_TIMEOUT) {
List<Programe> processList = procInfo.getRunningProcess(context);
for (Programe programe : processList) {
if ((programe.getPackageName() != null) && (programe.getPackageName().equals(packageName))) {
pid = programe.getPid();
Log.d(LOG_TAG, "pid:" + pid);
uid = programe.getUid();
if (pid != 0) {
isProcessStarted = true;
break;
}
}
}
if (isProcessStarted) {
break;
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "service onStart");
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)
.setContentTitle("Emmagee");
startForeground(startId, builder.build());
pid = intent.getExtras().getInt("pid");
uid = intent.getExtras().getInt("uid");
packageName = intent.getExtras().getString("package");
Log.d(LOG_TAG, "packageName======"+packageName);
Intent startIntent = getPackageManager().getLaunchIntentForPackage(packageName);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startIntent);
waitForAppStart(packageName,getBaseContext());
startActivity = intent.resolveActivity(getPackageManager()).getShortClassName();
processName = intent.getExtras().getString("processName");
packageName = intent.getExtras().getString("packageName");
startActivity = intent.getExtras().getString("startActivity");
cpuInfo = new CpuInfo(getBaseContext(), pid, Integer.toString(uid));
readSettingInfo();
if (isFloating) {
......@@ -236,14 +264,14 @@ public class EmmageeService extends Service {
SharedPreferences preferences = Settings.getDefaultSharedPreferences(getApplicationContext());
int interval = preferences.getInt(Settings.KEY_INTERVAL, 5);
delaytime = interval * 1000;
isFloating = preferences.getBoolean(Settings.KEY_ISFLOAT, true);
isFloating = preferences.getBoolean(Settings.KEY_ISFLOAT, false);
sender = preferences.getString(Settings.KEY_SENDER, BLANK_STRING);
password = preferences.getString(Settings.KEY_PASSWORD, BLANK_STRING);
recipients = preferences.getString(Settings.KEY_RECIPIENTS, BLANK_STRING);
receivers = recipients.split("\\s+");
smtp = preferences.getString(Settings.KEY_SMTP, BLANK_STRING);
isRoot = preferences.getBoolean(Settings.KEY_ROOT, false);
isAutoStop = preferences.getBoolean(Settings.KEY_AUTO_STOP, true);
isAutoStop = preferences.getBoolean(Settings.KEY_AUTO_STOP, false);
}
/**
......@@ -258,49 +286,33 @@ public class EmmageeService extends Service {
mDateTime = formatter.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
else
mDateTime = formatter.format(cal.getTime().getTime());
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
// 在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";
} else {
resultFilePath = getBaseContext().getFilesDir().getPath() + File.separator + "Emmagee_TestResult_" + mDateTime + ".csv";
}
resultFilePath = PERF_MONITOR_FILE;
try {
File resultFile = new File(resultFilePath);
resultFile.createNewFile();
Log.d(LOG_TAG, "*** resultFilePath ***"+resultFilePath);
boolean createDir = new File(PERF_MONITOR_DIR).mkdirs();
Log.d(LOG_TAG, "*** createDir ***"+createDir);
boolean createFile = resultFile.createNewFile();
Log.d(LOG_TAG, "*** createFile ***"+createFile);
out = new FileOutputStream(resultFile);
osw = new OutputStreamWriter(out);
osw = new OutputStreamWriter(out,"GBK");
bw = new BufferedWriter(osw);
long totalMemorySize = memoryInfo.getTotalMemory();
String totalMemory = fomart.format((double) totalMemorySize / 1024);
String multiCpuTitle = BLANK_STRING;
// titles of multiple cpu cores
ArrayList<String> cpuList = cpuInfo.getCpuList();
for (int i = 0; i < cpuList.size(); i++) {
multiCpuTitle += Constants.COMMA + cpuList.get(i) + getString(R.string.total_usage);
}
bw.write(getString(R.string.process_package) + Constants.COMMA + packageName + Constants.LINE_END + getString(R.string.process_name)
+ Constants.COMMA + processName + Constants.LINE_END + getString(R.string.process_pid) + Constants.COMMA + pid
+ Constants.LINE_END + getString(R.string.mem_size) + Constants.COMMA + totalMemory + "MB" + Constants.LINE_END
+ getString(R.string.cpu_type) + Constants.COMMA + cpuInfo.getCpuName() + Constants.LINE_END
+ getString(R.string.android_system_version) + Constants.COMMA + memoryInfo.getSDKVersion() + Constants.LINE_END
+ getString(R.string.mobile_type) + Constants.COMMA + memoryInfo.getPhoneType() + Constants.LINE_END + "UID" + Constants.COMMA
+ uid + Constants.LINE_END);
if (isGrantedReadLogsPermission()) {
bw.write(START_TIME);
}
if (isRoot) {
heapData = getString(R.string.native_heap) + Constants.COMMA + getString(R.string.dalvik_heap) + Constants.COMMA;
}
bw.write(getString(R.string.timestamp) + Constants.COMMA + getString(R.string.top_activity) + Constants.COMMA + heapData
// ArrayList<String> cpuList = cpuInfo.getCpuList();
// for (int i = 0; i < cpuList.size(); i++) {
// multiCpuTitle += Constants.COMMA + cpuList.get(i) + getString(R.string.total_usage);
// }
// 用例,时间,栈顶activity,pss,内存占比,剩余内存,cpu占比,cpu总占比,流量,电量,电流,电池温度,电压
bw.write("测试用例信息" + Constants.COMMA + getString(R.string.timestamp) + Constants.COMMA + getString(R.string.top_activity) + Constants.COMMA
+ getString(R.string.used_mem_PSS) + Constants.COMMA + getString(R.string.used_mem_ratio) + Constants.COMMA
+ getString(R.string.mobile_free_mem) + Constants.COMMA + getString(R.string.app_used_cpu_ratio) + Constants.COMMA
+ getString(R.string.total_used_cpu_ratio) + multiCpuTitle + Constants.COMMA + getString(R.string.traffic) + Constants.COMMA
+ getString(R.string.battery) + Constants.COMMA + getString(R.string.current) + Constants.COMMA + getString(R.string.temperature)
+ Constants.COMMA + getString(R.string.voltage) + Constants.LINE_END);
bw.flush();
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage());
}
......@@ -415,7 +427,7 @@ public class EmmageeService extends Service {
line = line.substring(0, line.indexOf("total"));
}
startTime = line.substring(line.lastIndexOf("+") + 1, line.lastIndexOf("ms") + 2);
Toast.makeText(EmmageeService.this, getString(R.string.start_time) + startTime, Toast.LENGTH_LONG).show();
Toast.makeText(MainService.this, getString(R.string.start_time) + startTime, Toast.LENGTH_LONG).show();
isGetStartTime = false;
break;
}
......@@ -444,6 +456,7 @@ public class EmmageeService extends Service {
* @throws IOException
*/
private void dataRefresh() {
Log.d(LOG_TAG, "*** dataRefresh ***");
int pidMemory = memoryInfo.getPidMemorySize(pid, getBaseContext());
long freeMemory = memoryInfo.getFreeMemorySize(getBaseContext());
String freeMemoryKb = fomart.format((double) freeMemory / 1024);
......@@ -527,8 +540,8 @@ public class EmmageeService extends Service {
public void closeOpenedStream() {
try {
if (bw != null) {
bw.write(getString(R.string.comment1) + Constants.LINE_END + getString(R.string.comment2) + Constants.LINE_END
+ getString(R.string.comment3) + Constants.LINE_END + getString(R.string.comment4) + Constants.LINE_END);
// bw.write(getString(R.string.comment1) + Constants.LINE_END + getString(R.string.comment2) + Constants.LINE_END
// + getString(R.string.comment3) + Constants.LINE_END + getString(R.string.comment4) + Constants.LINE_END);
bw.close();
}
if (osw != null)
......@@ -567,7 +580,7 @@ public class EmmageeService extends Service {
if (isSendSuccessfully) {
Toast.makeText(this, getString(R.string.send_success_toast) + recipients, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getString(R.string.send_fail_toast) + EmmageeService.resultFilePath, Toast.LENGTH_LONG).show();
Toast.makeText(this, getString(R.string.send_fail_toast) + MainService.resultFilePath, Toast.LENGTH_LONG).show();
}
super.onDestroy();
stopForeground(true);
......@@ -593,7 +606,7 @@ public class EmmageeService extends Service {
reader.close();
// replace a word in a file
String newtext = oldtext.replaceAll(replaceType, replaceString);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), getString(R.string.csv_encoding)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "GBK"));
writer.write(newtext);
writer.close();
} catch (IOException e) {
......
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
/**
* Constant Class
......@@ -12,5 +12,7 @@ public final class Constants {
public static final String COMMA = ",";
public static final String LINE_END = "\r\n";
public static final String COLON = ":";
public static final int WAIT_START_TIMEOUT = 20000;
}
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.io.File;
import java.io.FileFilter;
......@@ -29,13 +29,13 @@ import java.util.Calendar;
import java.util.Locale;
import java.util.regex.Pattern;
import com.netease.qa.emmagee.service.EmmageeService;
import com.netease.performancetestservice.MainService;
import com.netease.performancetestservice.R;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.netease.qa.emmagee.R;
/**
* operate CPU information
......@@ -76,7 +76,7 @@ public class CpuInfo {
this.pid = pid;
this.context = context;
trafficInfo = new TrafficInfo(uid);
formatterFile = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatterFile = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
mi = new MemoryInfo();
totalMemorySize = mi.getTotalMemory();
cpuUsedRatio = new ArrayList<String>();
......@@ -123,6 +123,7 @@ public class CpuInfo {
idleCpu.add(Long.parseLong(toks[4]));
totalCpu.add(Long.parseLong(toks[1]) + Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[5]) + Long.parseLong(toks[7]));
break;
}
cpuInfo.close();
} catch (FileNotFoundException e) {
......@@ -312,10 +313,13 @@ public class CpuInfo {
String[][] heapArray = MemoryInfo.getHeapSize(pid, context);
heapData = heapArray[0][1]+"/"+heapArray[0][0]+Constants.COMMA+heapArray[1][1]+"/"+heapArray[1][0]+Constants.COMMA;
}
EmmageeService.bw.write(mDateTime2 + Constants.COMMA + ProcessInfo.getTopActivity(context) + Constants.COMMA +heapData+ pMemory
Log.d(LOG_TAG, "*** Start write to performance file ***");
MainService.bw.write("No TestCase Info-No Action Info,"+mDateTime2 + Constants.COMMA + ProcessInfo.getTopActivity(context) + Constants.COMMA +heapData+ pMemory
+ Constants.COMMA + percent + Constants.COMMA + fMemory + Constants.COMMA + processCpuRatio + Constants.COMMA
+ totalCpuBuffer.toString() + trafValue + Constants.COMMA + totalBatt + Constants.COMMA + currentBatt + Constants.COMMA
+ temperature + Constants.COMMA + voltage + Constants.LINE_END);
MainService.bw.flush();
Log.d(LOG_TAG, "*** End write to performance file ***");
totalCpu2 = (ArrayList<Long>) totalCpu.clone();
processCpu2 = processCpu;
idleCpu2 = (ArrayList<Long>) idleCpu.clone();
......
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.io.BufferedReader;
import java.io.DataInputStream;
......
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import javax.mail.*;
......
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.security.*;
......
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.io.File;
import java.util.Date;
......
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
......
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import android.app.Application;
import android.view.WindowManager;
......
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.util.ArrayList;
import java.util.Collections;
......@@ -124,4 +124,6 @@ public class ProcessInfo {
else
return null;
}
}
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import android.graphics.drawable.Drawable;
......
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import android.content.Context;
import android.content.SharedPreferences;
......
......@@ -14,7 +14,7 @@
* limitations under the License.
*
*/
package com.netease.qa.emmagee.utils;
package com.netease.performancetestservice.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
......
/*
* 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.
*
*/
package com.netease.qa.emmagee.activity;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.netease.qa.emmagee.R;
/**
* About Page of Emmagee
*
* @author andrewleo
*/
public class AboutActivity extends Activity {
private static final String LOG_TAG = "Emmagee-"
+ AboutActivity.class.getSimpleName();
private TextView appVersion;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.about);
appVersion = (TextView)findViewById(R.id.app_version);
appVersion.setText(getVersion());
TextView title = (TextView)findViewById(R.id.nb_title);
title.setText(R.string.about);
ImageView btnSave = (ImageView) findViewById(R.id.btn_set);
btnSave.setVisibility(ImageView.INVISIBLE);
LinearLayout layGoBack = (LinearLayout) findViewById(R.id.lay_go_back);
layGoBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
AboutActivity.this.finish();
}
});
}
/**
* get app version
* @return app version
*/
public String getVersion() {
try {
PackageManager manager = this.getPackageManager();
PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
String version = info.versionName;
return version;
} catch (Exception e) {
e.printStackTrace();
return "-";
}
}
@Override
public void finish() {
super.finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
/*
* 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.
*
*/
package com.netease.qa.emmagee.activity;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.netease.qa.emmagee.R;
import com.netease.qa.emmagee.utils.EncryptData;
import com.netease.qa.emmagee.utils.Settings;
/**
* Mail Setting Page of Emmagee
*
* @author andrewleo
*/
public class MailSettingsActivity extends Activity {
private static final String LOG_TAG = "Emmagee-" + MailSettingsActivity.class.getSimpleName();
private static final String BLANK_STRING = "";
private EditText edtRecipients;
private EditText edtSender;
private EditText edtPassword;
private EditText edtSmtp;
private String sender;
private String prePassword, curPassword;
private String recipients, smtp;
private String[] receivers;
private TextView title;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mail_settings);
final EncryptData des = new EncryptData("emmagee");
edtSender = (EditText) findViewById(R.id.sender);
edtPassword = (EditText) findViewById(R.id.password);
edtRecipients = (EditText) findViewById(R.id.recipients);
edtSmtp = (EditText) findViewById(R.id.smtp);
title = (TextView) findViewById(R.id.nb_title);
LinearLayout layGoBack = (LinearLayout) findViewById(R.id.lay_go_back);
LinearLayout layBtnSet = (LinearLayout) findViewById(R.id.lay_btn_set);
title.setText(R.string.mail_settings);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
sender = preferences.getString(Settings.KEY_SENDER, BLANK_STRING);
prePassword = preferences.getString(Settings.KEY_PASSWORD, BLANK_STRING);
recipients = preferences.getString(Settings.KEY_RECIPIENTS, BLANK_STRING);
smtp = preferences.getString(Settings.KEY_SMTP, BLANK_STRING);
edtRecipients.setText(recipients);
edtSender.setText(sender);
edtPassword.setText(prePassword);
edtSmtp.setText(smtp);
layGoBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MailSettingsActivity.this.finish();
}
});
layBtnSet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sender = edtSender.getText().toString().trim();
if (!BLANK_STRING.equals(sender) && !checkMailFormat(sender)) {
Toast.makeText(MailSettingsActivity.this, getString(R.string.sender_mail_toast) + getString(R.string.format_incorrect_format),
Toast.LENGTH_LONG).show();
return;
}
recipients = edtRecipients.getText().toString().trim();
receivers = recipients.split("\\s+");
for (int i = 0; i < receivers.length; i++) {
if (!BLANK_STRING.equals(receivers[i]) && !checkMailFormat(receivers[i])) {
Toast.makeText(MailSettingsActivity.this,
getString(R.string.receiver_mail_toast) + "[" + receivers[i] + "]" + getString(R.string.format_incorrect_format),
Toast.LENGTH_LONG).show();
return;
}
}
curPassword = edtPassword.getText().toString().trim();
smtp = edtSmtp.getText().toString().trim();
if (checkMailConfig(sender, recipients, smtp, curPassword) == -1) {
Toast.makeText(MailSettingsActivity.this, getString(R.string.info_incomplete_toast), Toast.LENGTH_LONG).show();
return;
}
SharedPreferences preferences = Settings.getDefaultSharedPreferences(getApplicationContext());
Editor editor = preferences.edit();
editor.putString(Settings.KEY_SENDER, sender);
try {
editor.putString(Settings.KEY_PASSWORD, curPassword.equals(prePassword) ? curPassword : des.encrypt(curPassword));
} catch (Exception e) {
editor.putString(Settings.KEY_PASSWORD, curPassword);
}
editor.putString(Settings.KEY_RECIPIENTS, recipients);
editor.putString(Settings.KEY_SMTP, smtp);
editor.commit();
Toast.makeText(MailSettingsActivity.this, getString(R.string.save_success_toast), Toast.LENGTH_LONG).show();
Intent intent = new Intent();
setResult(Activity.RESULT_FIRST_USER, intent);
MailSettingsActivity.this.finish();
}
});
}
@Override
public void finish() {
super.finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* check if mail configurations are available
*
* @param sender
* @param recipients
* @param smtp
* @param curPassword
* @return true: valid configurations
*
*/
private int checkMailConfig(String sender, String recipients, String smtp, String curPassword) {
if (!BLANK_STRING.equals(curPassword) && !BLANK_STRING.equals(sender) && !BLANK_STRING.equals(recipients) && !BLANK_STRING.equals(smtp)) {
return 1;
} else if (BLANK_STRING.equals(curPassword) && BLANK_STRING.equals(sender) && BLANK_STRING.equals(recipients) && BLANK_STRING.equals(smtp)) {
return 0;
} else
return -1;
}
/**
* check mail format
*
* @return true: valid email address
*/
private boolean checkMailFormat(String mail) {
String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*" + "[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(mail);
return m.matches();
}
}
/*
* 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.
*
*/
package com.netease.qa.emmagee.activity;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.netease.qa.emmagee.R;
import com.netease.qa.emmagee.service.EmmageeService;
import com.netease.qa.emmagee.utils.ProcessInfo;
import com.netease.qa.emmagee.utils.Programe;
/**
* Main Page of Emmagee
*
* @author andrewleo
*/
public class MainPageActivity extends Activity {
private static final String LOG_TAG = "Emmagee-" + MainPageActivity.class.getSimpleName();
private static final int TIMEOUT = 20000;
private List<Programe> processList;
private ProcessInfo processInfo;
private Intent monitorService;
private ListView lstViProgramme;
private Button btnTest;
private int pid, uid;
private boolean isServiceStop = false;
private UpdateReceiver receiver;
private TextView nbTitle;
private ImageView ivGoBack;
private ImageView ivBtnSet;
private LinearLayout layBtnSet;
private Long mExitTime = (long) 0;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "MainActivity::onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainpage);
initTitleLayout();
processInfo = new ProcessInfo();
btnTest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
monitorService = new Intent();
monitorService.setClass(MainPageActivity.this, EmmageeService.class);
if (getString(R.string.start_test).equals(btnTest.getText().toString())) {
ListAdapter adapter = (ListAdapter) lstViProgramme.getAdapter();
if (adapter.checkedProg != null) {
String packageName = adapter.checkedProg.getPackageName();
String processName = adapter.checkedProg.getProcessName();
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
String startActivity = "";
Log.d(LOG_TAG, packageName);
// clear logcat
try {
Runtime.getRuntime().exec("logcat -c");
} catch (IOException e) {
Log.d(LOG_TAG, e.getMessage());
}
try {
startActivity = intent.resolveActivity(getPackageManager()).getShortClassName();
startActivity(intent);
} catch (Exception e) {
Toast.makeText(MainPageActivity.this, getString(R.string.can_not_start_app_toast), Toast.LENGTH_LONG).show();
return;
}
waitForAppStart(packageName);
monitorService.putExtra("processName", processName);
monitorService.putExtra("pid", pid);
monitorService.putExtra("uid", uid);
monitorService.putExtra("packageName", packageName);
monitorService.putExtra("startActivity", startActivity);
startService(monitorService);
isServiceStop = false;
btnTest.setText(getString(R.string.stop_test));
} else {
Toast.makeText(MainPageActivity.this, getString(R.string.choose_app_toast), Toast.LENGTH_LONG).show();
}
} else {
btnTest.setText(getString(R.string.start_test));
Toast.makeText(MainPageActivity.this, getString(R.string.test_result_file_toast) + EmmageeService.resultFilePath,
Toast.LENGTH_LONG).show();
stopService(monitorService);
}
}
});
lstViProgramme.setAdapter(new ListAdapter());
lstViProgramme.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
RadioButton rdBtn = (RadioButton) ((LinearLayout) view).getChildAt(0);
rdBtn.setChecked(true);
}
});
nbTitle.setText(getString(R.string.app_name));
ivGoBack.setVisibility(ImageView.INVISIBLE);
ivBtnSet.setImageResource(R.drawable.settings_button);
layBtnSet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
goToSettingsActivity();
}
});
receiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(EmmageeService.SERVICE_ACTION);
registerReceiver(receiver, filter);
}
private void initTitleLayout() {
ivGoBack = (ImageView) findViewById(R.id.go_back);
nbTitle = (TextView) findViewById(R.id.nb_title);
ivBtnSet = (ImageView) findViewById(R.id.btn_set);
lstViProgramme = (ListView) findViewById(R.id.processList);
btnTest = (Button) findViewById(R.id.test);
layBtnSet = (LinearLayout) findViewById(R.id.lay_btn_set);
}
/**
* customized BroadcastReceiver
*
* @author andrewleo
*/
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
isServiceStop = intent.getExtras().getBoolean("isServiceStop");
if (isServiceStop) {
btnTest.setText(getString(R.string.start_test));
}
}
}
@Override
protected void onStart() {
Log.d(LOG_TAG, "onStart");
super.onStart();
}
@Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume");
if (isServiceStop) {
btnTest.setText(getString(R.string.start_test));
}
}
/**
* wait for test application started.
*
* @param packageName
* package name of test application
*/
private void waitForAppStart(String packageName) {
Log.d(LOG_TAG, "wait for app start");
boolean isProcessStarted = false;
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < startTime + TIMEOUT) {
processList = processInfo.getRunningProcess(getBaseContext());
for (Programe programe : processList) {
if ((programe.getPackageName() != null) && (programe.getPackageName().equals(packageName))) {
pid = programe.getPid();
Log.d(LOG_TAG, "pid:" + pid);
uid = programe.getUid();
if (pid != 0) {
isProcessStarted = true;
break;
}
}
}
if (isProcessStarted) {
break;
}
}
}
/**
* show a dialog when click return key.
*
* @return Return true to prevent this event from being propagated further,
* or false to indicate that you have not handled this event and it
* should continue to be propagated.
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
Toast.makeText(this, R.string.quite_alert, Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis();
} else {
if (monitorService != null) {
Log.d(LOG_TAG, "stop service");
stopService(monitorService);
}
Log.d(LOG_TAG, "exit Emmagee");
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void goToSettingsActivity() {
Intent intent = new Intent();
intent.setClass(MainPageActivity.this, SettingsActivity.class);
startActivityForResult(intent, Activity.RESULT_FIRST_USER);
}
/**
* customizing adapter.
*
* @author andrewleo
*/
private class ListAdapter extends BaseAdapter {
List<Programe> programes;
Programe checkedProg;
int lastCheckedPosition = -1;
public ListAdapter() {
programes = processInfo.getRunningProcess(getBaseContext());
}
@Override
public int getCount() {
return programes.size();
}
@Override
public Object getItem(int position) {
return programes.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Programe pr = (Programe) programes.get(position);
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.list_item, parent, false);
Viewholder holder = (Viewholder) convertView.getTag();
if (holder == null) {
holder = new Viewholder();
convertView.setTag(holder);
holder.imgViAppIcon = (ImageView) convertView.findViewById(R.id.image);
holder.txtAppName = (TextView) convertView.findViewById(R.id.text);
holder.rdoBtnApp = (RadioButton) convertView.findViewById(R.id.rb);
holder.rdoBtnApp.setFocusable(false);
holder.rdoBtnApp.setOnCheckedChangeListener(checkedChangeListener);
}
holder.imgViAppIcon.setImageDrawable(pr.getIcon());
holder.txtAppName.setText(pr.getProcessName());
holder.rdoBtnApp.setId(position);
holder.rdoBtnApp.setChecked(checkedProg != null && getItem(position) == checkedProg);
return convertView;
}
OnCheckedChangeListener checkedChangeListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
final int checkedPosition = buttonView.getId();
if (lastCheckedPosition != -1) {
RadioButton tempButton = (RadioButton) findViewById(lastCheckedPosition);
if ((tempButton != null) && (lastCheckedPosition != checkedPosition)) {
tempButton.setChecked(false);
}
}
checkedProg = programes.get(checkedPosition);
lastCheckedPosition = checkedPosition;
}
}
};
}
/**
* save status of all installed processes
*
* @author andrewleo
*/
static class Viewholder {
TextView txtAppName;
ImageView imgViAppIcon;
RadioButton rdoBtnApp;
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
/*
* 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.
*
*/
package com.netease.qa.emmagee.activity;
import java.io.DataOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.netease.qa.emmagee.R;
import com.netease.qa.emmagee.utils.Settings;
/**
* Setting Page of Emmagee
*
* @author andrewleo
*/
public class SettingsActivity extends Activity {
private static final String LOG_TAG = "Emmagee-" + SettingsActivity.class.getSimpleName();
private CheckBox chkFloat;
private CheckBox chkRoot;
private CheckBox chkAutoStop;
private TextView tvTime;
private LinearLayout about;
private LinearLayout mailSettings;
private SharedPreferences preferences;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settings);
chkFloat = (CheckBox) findViewById(R.id.floating);
chkRoot = (CheckBox) findViewById(R.id.is_root);
chkAutoStop = (CheckBox) findViewById(R.id.auto_stop);
tvTime = (TextView) findViewById(R.id.time);
about = (LinearLayout) findViewById(R.id.about);
mailSettings = (LinearLayout) findViewById(R.id.mail_settings);
SeekBar timeBar = (SeekBar) findViewById(R.id.timeline);
ImageView btnSave = (ImageView) findViewById(R.id.btn_set);
RelativeLayout floatingItem = (RelativeLayout) findViewById(R.id.floating_item);
RelativeLayout autoStopItem = (RelativeLayout) findViewById(R.id.auto_stop_item);
LinearLayout layGoBack = (LinearLayout) findViewById(R.id.lay_go_back);
LinearLayout layHeapItem = (LinearLayout) findViewById(R.id.heap_item);
btnSave.setVisibility(ImageView.INVISIBLE);
preferences = Settings.getDefaultSharedPreferences(getApplicationContext());
int interval = preferences.getInt(Settings.KEY_INTERVAL, 5);
boolean isfloat = preferences.getBoolean(Settings.KEY_ISFLOAT, true);
boolean isRoot = preferences.getBoolean(Settings.KEY_ROOT, false);
boolean autoStop = preferences.getBoolean(Settings.KEY_AUTO_STOP, true);
tvTime.setText(String.valueOf(interval));
chkFloat.setChecked(isfloat);
chkRoot.setChecked(isRoot);
chkAutoStop.setChecked(autoStop);
timeBar.setProgress(interval);
timeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
tvTime.setText(Integer.toString(arg1 + 1));
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
// when tracking stoped, update preferences
int interval = arg0.getProgress() + 1;
preferences.edit().putInt(Settings.KEY_INTERVAL, interval).commit();
}
});
layGoBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SettingsActivity.this.finish();
Intent intent = new Intent();
intent.setClass(SettingsActivity.this, MainPageActivity.class);
startActivity(intent);
}
});
mailSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(SettingsActivity.this, MailSettingsActivity.class);
startActivity(intent);
}
});
about.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(SettingsActivity.this, AboutActivity.class);
startActivity(intent);
}
});
floatingItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
boolean isChecked = chkFloat.isChecked();
chkFloat.setChecked(!isChecked);
preferences.edit().putBoolean(Settings.KEY_ISFLOAT, !isChecked).commit();
}
});
autoStopItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
boolean isChecked = chkAutoStop.isChecked();
chkAutoStop.setChecked(!isChecked);
preferences.edit().putBoolean(Settings.KEY_AUTO_STOP, !isChecked).commit();
}
});
// get root permission
layHeapItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// if root checkbox is checked, change status to
// opposite;otherwise, try to upgrade app to root
boolean isChecked = chkRoot.isChecked();
if (isChecked) {
chkRoot.setChecked(!isChecked);
preferences.edit().putBoolean(Settings.KEY_ROOT, !isChecked).commit();
} else {
boolean root = upgradeRootPermission(getPackageCodePath());
if (root) {
Log.d(LOG_TAG, "root succeed");
chkRoot.setChecked(!isChecked);
preferences.edit().putBoolean(Settings.KEY_ROOT, !isChecked).commit();
} else {
// if root failed, tell user to check if phone is rooted
Toast.makeText(getBaseContext(), getString(R.string.root_failed_notification), Toast.LENGTH_LONG).show();
}
}
}
});
}
@Override
public void finish() {
super.finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* upgrade app to get root permission
*
* @return is root successfully
*/
public static boolean upgradeRootPermission(String pkgCodePath) {
Process process = null;
DataOutputStream os = null;
try {
String cmd = "chmod 777 " + pkgCodePath;
process = Runtime.getRuntime().exec("su"); // 切换到root帐号
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "\n");
os.writeBytes("exit\n");
os.flush();
int existValue = process.waitFor();
if (existValue == 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
Log.w(LOG_TAG, "upgradeRootPermission exception=" + e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册