一、 服务(Service)
1.定义和使用:
Android 中实现程序后台运行的解决方(使用时需要在AndroidManifest.xml中进行注册<service android:name=" XXXService "> </service>)
2.常用方法:
onBind(): 抽象方法,活动和服务的桥梁(可让一个内部类如testBinder继承Binder类,封装要实现的操作,然后在onBind()方法中return testbinder)
onCreate():服务创建时调用,只会调用一次
onStartCommand():服务启动时调用,可重复调用
onDestroy():服务结束时调用
3.启动服务的两种方式:
A.使用startService(intent)方法:仅仅是启动服务,此时Activity和服务处于无关状态,stopService()为对应的停止服务方法
B.绑定服务(让活动和服务紧密连接):需要用到ServiceConnection方法,代码如下:private ServiceCinnection conn = new ServiceConnection(){
@Override
public void onServiceConnected(CompomentName name, IBinder service){
//testBinder = service; testBinder下的方法
}
}
Main(){
//绑定服务,第一个参数为intent,第二个参数为ServiceCinnection实例,第三个参数为标志位,BIND_AUTO_CREATE表示绑定后自动创建服务,即onCreate方法得到执行
bindService(intent, conn,BIND_AUTO_CREATE);
//解绑服务
unbindService(conn);
}
注意:当对一个服务即调用startService()方法,又调用bindService()方法时,要销毁服务就要同时调用stopService()和unbindService()方法。
4.前台服务:希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑前台服务,它会一直在系统状态栏显示,非常类似通知的效果。(比如墨迹天气,它的服务在后台更新天气数据,还会在系统状态栏一直显示天气信息)
二、Android数据存储方式
1.五种方法比较:
A.文件存储数据:存放大量数据,如音频,图片等,可存入SDcard中。
B .SharedPreferences(使用键值对的方式存储数据):保存少量数据,且数据格式相对简单,不能程序间共享数据。
C.SQLite数据库:利用很少的内存且没有服务进程,所有数据存放在同一文件中,可自由复制。
D.ContentProvidor存储数据:可用于程序间共享数据,有增删改查功能。
E.网络存数据:通过网络来实现数据的存储和获取。
2.文件存储例子:
从EditText获取文本存入SDcard,然后重新打开程序后能把文本显示回在EditText中:
private String filename = "0TxT/test2.txt"; //具体EditText实现此处忽略
public void saveData(String str)
{
BufferedWriter bw1 = null;
FileOutputStream fos1 = null;
try{
boolean test = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if(test)
{
Log.d("abc",str);
File f = new File(Environment.getExternalStorageDirectory(),filename);
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
/*if(!f.exists()){
boolean isSuccess=f.createNewFile();
Log.d("abc","isSuccess="+isSuccess);
}*/
fos1= new FileOutputStream(f);
fos1.write(str.getBytes("UTF-8"));
fos1.flush();
}
else{
//Log.d("abc","not sdcard");
fos1 = openFileOutput(filename, Context.MODE_PRIVATE);
bw1 =new BufferedWriter(new OutputStreamWriter(fos1));
bw1.write(str);
}
} catch (Exception e) {
e.printStackTrace();
Log.d("abc", "Exception e = " +e.getMessage());
} finally {
try {
if(bw1 != null){
bw1.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
public String loadData()
{
BufferedReader br1 = null;
FileInputStream fis1 ;
String line = "";
String str = "";
// StringBuilder content = new StringBuilder();
try{
boolean test = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if(test)
{
//Log.d("abc","have sdcard");
File f = new File(Environment.getExternalStorageDirectory(),filename);
fis1 = new FileInputStream(f);
br1 = new BufferedReader(new InputStreamReader(fis1));
str = br1.readLine();
while ((line=br1.readLine())!= null){
str += "\n"+line;
}
}
else {
fis1 =openFileInput(filename);
br1 = new BufferedReader(new InputStreamReader(fis1));
str = br1.readLine();
while ((line=br1.readLine())!= null){
str += "\n"+line;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br1 !=null) {
try {
br1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return content.toString();
return str;
}
3.网络存储例子:
从网络获取图片并存入SDCard中:
private static final String PATH = Environment.getExternalStorageDirectory()+"/0Pic_Load/";
private static final String SERVER_URL ="http://images.cnblogs.com/cnblogs_com/mandroid/201104/201104050128502247.png";
public static URL url2 = null;
public HttpURLConnection conn2 = null;
public static Bitmap bm = null;
private ImageView img2;
private ImageView img_network;
public HttpURLConnection getConn(URL urltest)
{
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) urltest.openConnection();
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
//以get方式请求
connection.setRequestMethod("GET");
if(connection.getResponseCode()!=200)
{
throw new RuntimeException("请求URL失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public void getNetworkPicandSave()
{
new Thread(){
public void run(){
//获得url
try {
url2 = new URL(SERVER_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
conn2 = getConn(url2);//获得连接对象
InputStream is2 = null;
try {
is2 = conn2.getInputStream(); //得到网络返回的输入流
bm = BitmapFactory.decodeStream(is2);//bm为数据流转图片
//存储图片,flag=1证明存储成功
int flag = savePic("test.jpg", bm);
if (flag==1){
Toast.makeText(NetworkdataActivity.this , "Save Pic Success,in Path:"+PATH, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.d("abc", "e1 = " + String.valueOf(e));
}
try {
if(is2!=null)
{
is2.close();
conn2.disconnect();
}
} catch (IOException e) {
Log.d("abc", "e2 = " + String.valueOf(e));
}
}
}.start();
}
public int savePic(String filename,Bitmap bmImg)
{
Log.d("abc","pic save");
//显示出来后进行保存
//BufferedWriter bw1 = null;
try{
boolean test = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if(String.valueOf(test).equals("true"))
{
File f = new File(PATH,filename);
//Log.d("abc","path:"+f.getParentFile().getAbsolutePath());
/*if (!f.exists()) {
f.createNewFile();
}*/
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fos1= new FileOutputStream(f);
if(!fos1.equals(null)) {
bmImg.compress(Bitmap.CompressFormat.PNG, 90, fos1);
fos1.flush();
fos1.close();
return 1;
//保存成功返回1
}
//Toast.makeText(this,"Have been save in: "+PATH , Toast.LENGTH_SHORT).show();
}
else{
Log.d("abc","not sdcard");
}
} catch (Exception e) {
e.printStackTrace();
Log.d("abc", "Exception e = " +e.getMessage());
}
return 0;
}