Service
来源:互联网 发布:传奇霸业宝石数据 编辑:程序博客网 时间:2024/05/18 03:21
服务需要在清单文件中注册
Started service
1.服务同时只会被创建一次,可以通过外部调用Stopservice来终止服务
2.当执行一个已启动的服务,会直接调用onStartCommand方法来执行业务
3.默认情况下服务与主线程在同一线程下,所有会执行主线程,服务里面调用线程
4.使用startService启动的服务,如果不关闭,会一直在后台运行
onStartCommand会返回一个整形,返回四个值
1.START_STICKY 当服务被kill掉,会重启服务,粘性的 不保留传递的intent对象
2.START_NOT_STICKY 非粘性的 如果被kill掉,不会重启服务
3.START_REDELIVER_INTENT 如果服务被异常kill掉 重传intent对象,
4.START_STICKY_COMPATIBILITY 是START_STICKY兼容版本,但保证服务重启
IntentService
IntentService是继承于Service并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作
,启动Intentservice和启动Service一样,同时,执行完任务后,它会自动停止服务,不需要手动关闭。
它可以启动多次,每一个耗时操作都会排成一列,一个执行完再执行另一个
启动和关闭一个简单的服务示例:
//启动一个服务 public void StartServer(View v){ Intent intent=new Intent(this,MyServer.class); //intent.putExtra("tag", "扶朕起来,朕还能学"); startService(intent); } //关闭一个服务 public void StopServer(View v){ Intent intent=new Intent(this,MyServer.class); stopService(intent); //停止服务时会调用ondestory()方法 }
服务类
public class MyServer extends Service{ @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub String st = intent.getStringExtra("tag"); Log.i("打印",st); Toast.makeText(getApplicationContext(), st, 1).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.i("打印","服务已销毁"); super.onDestroy(); }}
注册服务
<service android:name=".MyServer" android:enabled="true" android:exported="true" > </service> <service android:name=".IntentServiceTest" android:enabled="true" android:exported="false" > <!-- exported 内部可以访问 --> </service>
一个Intentservice示例(上面已注册):
public class IntentServiceTest extends IntentService{ public IntentServiceTest() { super("IntentServiceTest"); // TODO Auto-generated constructor stub } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub String st = intent.getStringExtra("tag"); Log.i("打印",st); for(int i=0;i<50;i++){ System.out.println(i+Thread.currentThread().getName()); } }}
启动一个Intentservcice
public void StatIntentService(View v){ Intent intent=new Intent(this,IntentServiceTest.class); intent.putExtra("tag", "扶朕起来"); startService(intent); //停止服务时会调用ondestory()方法 }
0 0
- Service
- Service
- service
- Service
- service
- Service
- Service
- service
- Service
- Service
- Service
- service
- service
- Service
- Service
- Service
- Service
- Service
- Java字符串深入理解
- poj 3264
- Android知识要点整理(16)----Gradle 之项目结构
- HDU 1269 迷宫城堡
- mitaka版本openstack虚拟化云桌面的实现(spice)
- Service
- C语言字符串查找替换
- 分数化小数(decimal)完整版
- Forwar Rendering vs. Deferred Rendering
- .NET c# EF DB first 连接mysql 实施
- 史上最详细Windows版本搭建安装React Native环境配置
- SQL镜像
- HDU 5575 Discover Water Tank
- filesystem-e2fsprog