Service学习笔记-基础

今天学了android service,记录下一些知识点。

1、Service的生命周期

这里写图片描述

2、Service两种调用方式
方式1:

    activity中启动

            Intent intent1=new Intent(this, MyService.class);
            intent1.putExtra("intent1",1);
            startService(intent1);

    activity中终止

            stopService(new Intent(this, MyService.class));

   Service中参数调用

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Trace.d(TAG,”onStartCommand”);
if(intent!=null && intent.getIntExtra(“intent1”,0)==1) Trace.d(TAG,”onStartCommand,intent1”);
else if(intent!=null && intent.getIntExtra(“intent2”,0)==1) Trace.d(TAG,”onStartCommand,intent2”);
return START_STICKY;
}

方式2:

activity中启动

            bindService(new Intent(this, MyService.class), connection,BIND_AUTO_CREATE);




    private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        Trace.d(TAG,"onServiceConnected");
        //isBind=true;
        binder = (MyService.MyBinder) iBinder;
        binder.startDownload();
    }
    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        //isBind=false;
        Trace.d(TAG,"onServiceDisconnected");
    }
};

            try {
                unbindService(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }

activity中终止

try {
unbindService(connection);
} catch (Exception e) {
e.printStackTrace();
}

Service中方法调用

class MyBinder extends Binder{
public void startDownload(){
Trace.d(TAG,”start startDownload^^^^^^^^”);
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
try {
Thread.sleep(1000);
Trace.d(TAG,”new Thread(new Runnable()),i=”+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSelf();
}
}).start();
Trace.d(TAG,”end startDownload^^^^^^^^”);
}

3、前端服务
Intent notificationIntent=new Intent(this,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
Notification notification=new Notification.Builder(this)
.setSmallIcon(R.mipmap.icon)
.setLargeIcon(drawableToBitmap(getResources().getDrawable(R.mipmap.icon)))
.setContentTitle(“title”)
.setContentText(“Message”)
.setContentIntent(pendingIntent)
.getNotification();
startForeground(1,notification);

个人demo地址:http://download.csdn.net/detail/u013795543/9649857

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值