import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.decarta.db.MapVersionTable;
/**
* @author Tony Shen
*
*/
public class Main extends Activity {
private MapVersionTable mDB;
private String mapVersion;
private String apkUrl;
private List<RunningAppProcessInfo> process;
private ActivityManager activityMan;
private ProgressBar progressBar;
private final int CHECK_NEW_VERSION = 1;
private final int DOWNLOAD = 2;
private final int INSTALL = 3;
private final int CHECK_APP = 4;
private final int INVOKE_APP = 5;
private final int DOWNLOAD_AGAIN = 6;
private final int INSTALL_AGAIN = 7;
private boolean newVersionFlag = false;
private boolean checkAppFlag = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDB = new MapVersionTable(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.VISIBLE);
progressBar.setMax(100);
progressBar.setProgress(0);
checkAppFlag = checkApp();
new Thread(new Runnable() {
Message msg = new Message();
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
msg.what = CHECK_NEW_VERSION;
mHandler.sendMessage(msg);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (newVersionFlag) {
msg.what = DOWNLOAD;
mHandler.sendMessage(msg);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
msg.what = INSTALL;
mHandler.sendMessage(msg);
} else {
msg.what = CHECK_APP;
mHandler.sendMessage(msg);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (checkAppFlag) {
msg.what = INVOKE_APP;
mHandler.sendMessage(msg);
} else {
msg.what = DOWNLOAD_AGAIN;
mHandler.sendMessage(msg);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
msg.what = INSTALL_AGAIN;
mHandler.sendMessage(msg);
}
}
}
}).start();
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what){
case CHECK_NEW_VERSION:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "检查更新", Toast.LENGTH_SHORT).show();
newVersionFlag = checkNewVersion();
progressBar.setProgress(30);
}
break;
case DOWNLOAD:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "下载更新", Toast.LENGTH_SHORT).show();
downloadAPK(apkUrl);
progressBar.setProgress(60);
}
break;
case INSTALL:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "安装更新", Toast.LENGTH_SHORT).show();
killProcess();
progressBar.setProgress(100);
installAPK();
finish();
}
break;
case CHECK_APP:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "检查应用", Toast.LENGTH_SHORT).show();
// checkAppFlag = checkApp();
progressBar.setProgress(60);
}
break;
case INVOKE_APP:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "程序启动", Toast.LENGTH_SHORT).show();
progressBar.setProgress(100);
invokeAPK();
finish();
}
break;
case DOWNLOAD_AGAIN:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "下载更新", Toast.LENGTH_SHORT).show();
progressBar.setProgress(80);
downloadAPK(apkUrl);
}
break;
case INSTALL_AGAIN:
if(!Thread.currentThread().isInterrupted()){//当前线程正在运行
Toast.makeText(Main.this, "安装更新", Toast.LENGTH_SHORT).show();
progressBar.setProgress(100);
installAPK();
finish();
}
break;
default:
progressBar.setVisibility(View.GONE);
Thread.currentThread().interrupt();//中断当前线程.
break;
}
super.handleMessage(msg);
}
};
private boolean checkNewVersion() {
try {
URL url=new URL(/blog_article/AppConfig.SERVLET_URL);
SAXParserFactory factory=SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
SAXParser parser=factory.newSAXParser();
InputStream is = url.openStream();
parser.parse(is, new DefaultHandler(){
private String cur="";
private int step;
@Override
public void startDocument() throws SAXException {
step = 0;
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
cur = localName;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String str = new String(ch, start, length).trim();
if (str == null || str.equals(""))
return;
if (cur.equals("url")) {
apkUrl = str;
}
if (cur.equals("map_version")) {
mapVersion = str;
}
}
@Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
step = step + 1;
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (diffVersion(mapVersion))
return true;
else
return false;
}
private boolean diffVersion(String mapVersion) {
String lastVersion = mDB.getLastMapVersion();
if (lastVersion == null) {
mDB.setMapVersion(mapVersion);
return true;
}
if (!lastVersion.equals(mapVersion)) {
mDB.setMapVersion(mapVersion);
return true;
}
else
return false;
}
private void downloadAPK(String apkUrl) {
String filePath = "//sdcard//download//" + AppConfig.APKNAME;
URL url = null;
try {
url = new URL(/blog_article/apkUrl/index.html);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream in = con.getInputStream();
File fileOut = new File(filePath);
FileOutputStream out = new FileOutputStream(fileOut);
byte[] bytes = new byte[1024];
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void killProcess() {
activityMan = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
process = activityMan.getRunningAppProcesses();
int len = process.size();
for(int i = 0;i<len;i++) {
if (process.get(i).processName.equals(AppConfig.PKG)) {
android.os.Process.killProcess(process.get(i).pid);
}
}
}
private void installAPK() {
String fileName = getSDPath() +"/download/"+AppConfig.APKNAME;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
startActivity(intent);
}
private void invokeAPK() {
Intent i=new Intent();
i.setComponent(new ComponentName(AppConfig.PKG, AppConfig.CLS));
startActivity(i);
}
private boolean checkApp() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.android.settings",
"com.android.settings.InstalledAppDetails");
intent.putExtra("com.android.settings.ApplicationPkgName",
AppConfig.APKNAME);
List<ResolveInfo> acts = getPackageManager().queryIntentActivities(
intent, 0);
if (acts.size() > 0)
return true;
else
return false;
}
private String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED); // determine whether sd card is exist
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();// get the root directory
}
return sdDir.toString();
}
@Override
public void finish() {
super.finish();
Thread.currentThread().interrupt();//中断当前线程.
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
mDB.close(); // be sure to close
} catch (Exception e) {
}
}
}
1. Service SDK翻译
自己的翻译 英语不好 硬着头皮翻译了些:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
Service服务 是一种能够在后台执行长时间任务 但不提供UI的应用组件
其他的应用组件可开始一个Service服务,是它在后台继续运行 甚至是进程间通信IPC
比如 一个Service可以处理网络传输,音乐播放,文件读写操作,或是使用content provider,这些都是后台运行的
Service
This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.、
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
Service
这是所有Service的父类,当你继承它时,一定要建立新的线程去执行Service的任务,因为这个service将会使用你应用的主线程,默认时他会拖慢你应用中正在运行的所有activity。
IntentService
这是一个Service的子类,它使用一个工作线程来一次一个的处理所有开始的请求。这是最好的选择,如果你不要求您的服务同时处理多个请求。你所要做的只是实现onHandleIntent()方法,用来接收处理每个intent请求,这些都是后台运行的。
Because most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using the IntentService class.
因为大部分开始的服务不需要同时处理多个请求(实际上这是一个危险的多线程的情况)。所以使用IntentService类实现服务可能是最好的方式了。
后面是摘自他人的 ,觉得不错转在这里,多多学习
2. Service的调用
(1)Context.startService():Service会经历onCreate -> onStart(如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次 );stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。 注意,多次调用Context.startservice()不会嵌套(即使会有相应的onStart()方法被调用),所以无论同一个服务被启动了多少次,一旦调用Context.stopService()或者stopSelf(),他都会被停止。补充说明:传递给startService()的Intent对象会传递给onStart()方法。调用顺序为:onCreate --> onStart(可多次调用) --> onDestroy。
(2)Context.bindService():Service会经历onCreate() -> onBind(),onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind -> onDestroyed相应退出,所谓绑定在一起就共存亡了 。
补充说明:传递给bindService()的Intent对象会传递给onBind(),传递给unbindService()的Intent对象会传递给onUnbind()方法。 调用顺序为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。
(3)注意事项:在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。还有一点,目前我没有遇到过需要startService和bindService交互使用的情况(我认为不会有这种需求),所以不必去考虑交互的问题,待遇到时再考虑不迟。
(4)BroadcastReceiver只能通过startService启动Service ,因为广播本身生命周期很短,bind的话没有意义:Method bindService can not be called from an BroadcastReceiver component. A pattern you can use to communicate from an BroadcastReceiver to a Service is to call startService(Intent) with the arguments containing the command to be sent, with the service calling its stopSelf(int) method when done executing that command. See the API demo App/Service/Service Start Arguments Controller for an illustration of this. It is okay, however, to use this method from an BroadcastReceiver that has been registered with registerReceiver(BroadcastReceiver, IntentFilter), since the lifetime of this BroadcastReceiver is tied to another object (the one that registered it).
3. 示例代码
(1)调用者Activity
(2)Service
4. 与远程Service通信(进程间Service通信)
如何两个进程间的Service需要进行通信,则需要把对象序列化后进行互相发送。
Android提供了一个 AIDL (Android接口定义语言)工具来处理序列化和通信。这种情况下Service需要以aidl文件的方式提供服务接口,AIDL工具将生成一个相应的java接口,并且在生成的服务接口中包含一个功能调用的stub服务桩类。Service的实现类需要去继承这个 stub服务桩类。Service的onBind方法会返回实现类的对象,之后你就可以使用它了,参见下例:
先创建一个IMyRemoteService.aidl文件,内容如下:
package com.wissen.testApp;
interface IMyRemoteService {
int getStatusCode();
}
如果你正在使用eclipse的 Android插件,则它会根据这个aidl文件生成一个Java接口类。生成的接口类中会有一个内部类Stub类,你要做的事就是去继承该Stub类:
package com.wissen.testApp;
class RemoteService implements Service {
int statusCode;
@Override
public IBinder onBind(Intent arg0) {
return myRemoteServiceStub;
}
private IMyRemoteService.Stub myRemoteServiceStub = new IMyRemoteService.Stub() {
public int getStatusCode() throws RemoteException {
return 0;
}
};
…
}
当客户端应用连接到这个Service时,onServiceConnected方法将被调用,客户端就可以获得IBinder对象。参看下面的客户端onServiceConnected方法:
…
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IMyRemoteService myRemoteService = IMyRemoteService.Stub.asInterface(service);
try {
statusCode = myRemoteService.getStatusCode();
} catch(RemoteException e) {
// handle exception
}
Log.i(”INFO”, “Service bound “);
}
…
};
java中判断字符串是否为数字的方法:
1.用JAVA自带的函数
public static boolean isNumeric(String str){ for (int i = 0; i < str.length(); i++){ System.out.println(str.charAt(i)); if (!Character.isDigit(str.charAt(i))){ return false; } } return true; }
2.用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str){ Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if( !isNum.matches() ){ return false; } return true; }
3.使用org.apache.commons.lang
org.apache.commons.lang.StringUtils; boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false StringUtils.isNumeric("") = true StringUtils.isNumeric(" ") = false StringUtils.isNumeric("123") = true StringUtils.isNumeric("12 3") = false StringUtils.isNumeric("ab2c") = false StringUtils.isNumeric("12-3") = false StringUtils.isNumeric("12.3") = false
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null
上面三种方式中,第二种方式比较灵活。
第一、三种方式只能校验不含负号“-”的数字,即输入一个负数-199,输出结果将是false;
而第二方式则可以通过修改正则表达式实现校验负数,将正则表达式修改为“^-?[0-9]+”即可,修改为“-?[0-9]+.?[0-9]+”即可匹配所有数字。