Android 服务之startService和bindService以及前台服务的创建

android服务一般用来做一些,后台操作,数据处理。比较常用。
android服务包括前台服务和后台服务.
前台服务一般用来做音乐的后台播放,可以在通知栏显示。
前台服务的创建:

public class ForegroundService extends Service {

@Override
    public void onCreate() {
        private NotificationManager mNM;
        Notification notification = new Notification(R.drawable.icon,  getText(R.string.ticker_text),System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, ExampleActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
        startForeground(ONGOING_NOTIFICATION, notification);
}

@Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }
}

服务的两种启动方式总结:
        startService启动服务后和activity就没关系了,启动多次也只会调用一次onCreate(),会调用多次onStart()。
        bindService将服务与activity绑定,activity可以调用service中的方法。

    代码例子:



public void class Myservice extends Service {

   @Override  
    public void onCreate()  
    { 
        super.onCreate();  

    }  
      //用于和外界交互  
   private final IBinder binder = new MyBinder();  

    public class MyBinder extends Binder  
    {  
        MyService getService()  
        {  
            return MyService.this;  
        }  
    }  
    @Override  
    public IBinder onBind(Intent intent)  
    {  

    }  

    @Override  
    public int onStartCommand(Intent intent, int flags, int startId)  
    {  

    }  

    @Override  
    public void onDestroy()  
    {  

    }  
    public void  给activity调用的方法(){}
}

在Activity中绑定服务

public void class MyActivity extends Activity{

private Myservice myservice;

private ServiceConnection mServiceConnection = new ServiceConnection()  
{  

    @Override  
    public void onServiceDisconnected(ComponentName name)  
    {  

    }  

    @Override  
    public void onServiceConnected(ComponentName name, IBinder service)   
    {  
        // bindService成功的时候返回service的引用  
        MyBinder myBinder = (MyBinder)service;  
        mMyService = myBinder.getService();  
    }  
}  

@Override  
    public void onCreate()  
    {  
        super.onCreate();  
        //启动服务  
        Intent intentService = new Intent(MyActivity.this, MyService.class);  
        intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
        intentService.setAction("scott");  
        //bindService用于和service进行交互  
        MyActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);  
        //startService用于启动service但是不和其交互  
        startService(intentService);  
    } 



}

“`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值