我们生活在一个以时间为线性序列的世界,但我们可以用空间来换取时间。
记得在小时候我们学过一种方法论,叫做统筹规划。
生活中有很多常见的现象:
例如我们可以一边用洗衣机洗衣服,一边用电饭煲烧饭,然后我们人就可以闲下来做其他的事情,比如说看电视,或者出门去逛街。
在Android世界中是否有这样的方法也可以这样做呢?是的,只要你想,就有可能。
这里,我们要学习到一个词“Service”
我们可以这样形象的比喻之前我们学的Activity,它是一个人机交互的界面。就好象是触动洗衣机洗衣的按钮、遥控器上的按钮、电视机上的画面。
我们也可以这样形象的比喻我们现在要学的Service,它就好像是一个“独立”的机器,例如是一台洗衣机,一台电饭煲。注意独立这个词:它的运行不需要我们进行过多的干预。
下面看一个程序也许能更加让你对于Service印象深刻:
进入画面
点击洗衣机洗衣服,或者电饭煲煮饭后,就可以去看电视了,
或者退出程序。
点击了看电视:
看电视大约看了50几秒的样子,突然会有一条消息发送过来:告诉你电饭煲的饭煮好了:
下面看程序吧:
这是MyService类,
package com.android.Yao;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class MyServices extends Service {
@Override
public void onCreate() {
super.onCreate();
}
private long mtime;
private String mwhat;
public void setOnTime(long time)
{
mtime = time;
}
public void setOnDoWhat(String dowhat)
{
mwhat = dowhat;
}
private void shownotification(String tab)
{
NotificationManager barmanager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification msg=new Notification(android.R.drawable.stat_notify_chat,tab,System.currentTimeMillis());
PendingIntent contentIntent=PendingIntent.getActivity(this, 0, new Intent(this,YaoFtp.class), PendingIntent.FLAG_ONE_SHOT);
//msg.setLatestEventInfo(this, "您好,"+mwhat+"已经完毕!"+"用时:"+mtime/1000+"秒钟!", "", contentIntent);
msg.setLatestEventInfo(this,"您好,工作完毕!" , "您的工作已经完毕!用时:"+60000/1000+"秒钟!", contentIntent);
barmanager.notify(0, msg);
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
shownotification("Hello AndroidQQ群697668来新的消息了");
}
}, 60000);
this.stopSelf();
}
}
这是点击洗衣机或者电饭煲按钮的操作:
intent=new Intent();
intent.setClass(YaoFtp.this, MyServices.class);
startService(intent);
点击看电视的操作:
intent=new Intent();
intent.setClass(YaoFtp.this, YaoTv.class);
startActivity(intent);