轻松几步学安卓Service

第一步修改androidmanifest文件,添加service android name

<application>
   <service android:name=".MyService"/>
</application>
第二步新建一个Myservice类文件,内容如下:
package com.example.android;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    private boolean running=false;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate(){
        super.onCreate();
        
        running=true;
        new Thread(){
            public void run(){
                super.run();
                
                while(running){
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        };
    }
//       @Override  
//        public int onStartCommand(Intent intent,int flags,int startId) {  
//           super.onStartCommand(intent, flags, startId);  
//           return START_STICKY;  
//        }
    
    @Override
    public void onDestroy(){
        super.onDestroy();
        
        running=false;
    }
}

第三步启用service或关闭service(分2种方式一种local service即程序1启动或关闭自己的服务,而remote service是通过程序2启动或关闭程序1的服务)

local service:

启用service:startService(new Intent(this, MyService.class)); 

关闭service:stopService(new Intent(this, MyService.class)); 

remote service:

启用程序1的service

Intent i=new Intent();

i.setComponent(new ComponentName("被启动的程序包名","被启动的程序service类名");

startService(i);

关闭程序1的service

Intent i=new Intent();

i.setComponent(new ComponentName("被启动的程序包名","被启动的程序service类名");

stopService(i);




参考http://www.cnblogs.com/wenjiang/p/3231986.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值