Service服务相关(1)

Service,服务,是android四大组件之一。使用场景:
1.一般用于执行长时间的事务。
2.可以在用户不可见的状态下处理事务。

使用:
1)通过 startService(intentS)方式启动服务:

package wy.bzt.com.phonehelper.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by wuyong on 2016/7/18.
 */
public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("ss","service onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ss","service onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("ss","service onDestroy");
    }
}

在activity中:

 intentS=new Intent(this, MyService.class);
        startService(intentS);

第一次启动服务,调用onCreate,onStartCommand,之后再启动服务,只会调用onStartCommand;注销服务,只需要stopService(intentS),或者在service中stopSelf()。

2)通过bind方式启动服务

public class MyBindService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("bbb","onCreate");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("bbb","onBind");
        return new MyBinder();

    }


    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("bbb","onUnbind");
        return super.onUnbind(intent);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("bbb","onDestroy");
    }

    public class MyBinder extends Binder{

        public MyBindService getBindService(){
            return MyBindService.this;
        }
    }
}

在activity中:

MyServiceConnection myServiceConnection;
    MyBindService.MyBinder myBinder;
    MyBindService bindService;
    Intent bindintent;
    boolean bind;
    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            myBinder= (MyBindService.MyBinder) service;
            bindService=myBinder.getBindService();

            bind=true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bind=false;
        }
    }
 bindintent=new Intent(this,MyBindService.class);
        bindService(bindintent,myServiceConnection,Context.BIND_AUTO_CREATE);

启动bindservice会调用onCreate,onBind方法,之后再启动的话,不会进行回调,调用unbindService(myServiceConnection)会触发onUnbind和onDestroy,事实上,用bind方式启动服务时,服务的生命周期会跟随activity的生命周期,activity结束,服务也自动结束。

一种常用的写法是:activity中启动服务,在服务中添加延时启动功能,到时候通过intent启动广播,广播中可以继续跳转至service(一般通过startservice方法),可以不断触发onStartCommand方法,达到某种目的;或者在activity中延时发送广播,在广播中启动服务,服务中开线程处理事务等等。

一个常用的类:intentservice
在studio中系统的例子:

public class MyIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_FOO = "wy.bzt.com.phonehelper.service.action.FOO";
    private static final String ACTION_BAZ = "wy.bzt.com.phonehelper.service.action.BAZ";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "wy.bzt.com.phonehelper.service.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "wy.bzt.com.phonehelper.service.extra.PARAM2";

    public MyIntentService() {
        super("MyIntentService");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionBaz(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionBaz(param1, param2);
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

其中需要注意的是:
1.onHandlerIntent默认在新的线程中运行,不需要再另外启动线程处理事务;
2.IntentService处理事务是按照队列一个个处理;
3.处理完成后,会自动结束service,不需要自己去关闭。

service的特点:
1.本身运行在所在进程的主线程,一般启动服务是为了处理长期事务,则需要在服务中启动线程处理,往往IntentService是更好的选择;

2.service 通过start方式启动后,如果不主动关闭,会一直在后台运行,很多时候会引起用户不满,所以最好在不需要的时候关掉它;

eg:
在activity中定时,一段时间后弹出个通知,点击通知,弹出个活动窗口;
关键代码:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ss","service onStartCommand");

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("new message")
                .setContentText("aaaaaaaa");
        mBuilder.setTicker("New message");//提示消息,显示在通知栏上,一会消失
        mBuilder.setNumber(12);
        //mBuilder.setLargeIcon();
        mBuilder.setAutoCancel(true);//自己维护通知的消失

        Intent resultIntent = new Intent(getApplicationContext(),MyActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // 设置通知主题的意图
        mBuilder.setContentIntent(resultPendingIntent);
        //获取通知管理器对象
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());

        return super.onStartCommand(intent, flags, startId);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值