intentservice的用法

intentService与service相比内部开启子线程,把耗时操作放到onHandleIntent方法中,与Activity的通信使用Binder,没毛病。以后使用到服务直接用intentService就可以啦,省时省力。
PS:service两套生命周期实际开发中合为一套 oncreate() onstartcommand() onBind() onUnbind() onDestroy()

以下代码为activity和intentservice通信问题
Activity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
   private TextView mTv;
    private Button mBt1,mBt2,mBt3,mBt4;
    private Intent intent;







    private ServiceConnection mServiceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(final ComponentName name, final IBinder service) {
            System.out.println("Activty启动,获取此时服务的数据");
            System.out.println("ComponentName = [" + name + "]");
            Log.e("1", "Activty启动,获取此时服务的数据 " );
            Log.e("1","ComponentName = [" + name + "]");

            MyIntentService2.MyBinder myBinder= (MyIntentService2.MyBinder) service;
            mTv.setText("这个服务的数字已经走到:"+  myBinder.getCount());
//            myBinder.dyfwff();
//            MyService myService=myBinder.mMyService;
//            myService.fwdff();
        }

        @Override
        public void onServiceDisconnected(final ComponentName name) {

        }
    };
    @Override
    public void onClick(View v) {
//        Intent mIntent=new Intent(this,TargetActivity.class);
//        mIntent.putExtra("person",mPerson);
//        startActivity(mIntent);

        switch (v.getId()){
//            case R.id.bt:
//                Intent mIntent=new Intent(this,TargetActivity.class);
//                mIntent.putExtra("mDog",mDog);
//                startActivity(mIntent);
//                break;
            case R.id.bt1:
                Log.e("1", "run:启动服务 " );

                startService(intent);
                break;
            case R.id.bt2:
                Log.e("1", "run:bind服务 " );
                bindService(intent,mServiceConnection, Service.BIND_AUTO_CREATE);
                break;
            case R.id.bt3:
                Log.e("1", "run:unbind服务 " );
                if(mServiceConnection!=null)
                unbindService(mServiceConnection);
                break;
            case R.id.bt4:
                Log.e("1", "run:stop服务 " );
                stopService(intent);
                break;
            default:

                break;

        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            unbindService(mServiceConnection);
        } catch (Exception e) {
            System.out.println("请先绑定服务再执行解绑");
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//        mBt = (Button)getFragmentManager().findFragmentById(R.id.layout_home_activity_root_frag).getView().findViewById(R.id.bt);
        mBt = (Button) findViewById(R.id.bt);
        mBt.setOnClickListener(this);
        mBt1 = (Button) findViewById(R.id.bt1);
        mBt1.setOnClickListener(this);
        mBt2 = (Button) findViewById(R.id.bt2);
        mBt2.setOnClickListener(this);
        mBt3 = (Button) findViewById(R.id.bt3);
        mBt3.setOnClickListener(this);
        mBt4 = (Button) findViewById(R.id.bt4);
        mBt4.setOnClickListener(this);
        mTv = (TextView) findViewById(R.id.tv);
        intent=new Intent(this,MyIntentService2.class);
//        addFragment(mFragment2);
    }


}

intentService

public class MyIntentService2 extends IntentService {

    private int count;
    private boolean mBoolean=true;
    public MyIntentService2() {
        super("MyIntentService2");
    }

    @Nullable
    @Override
    public IBinder onBind(final Intent intent) {
//        return super.onBind(intent);
        return new MyBinder();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            while (mBoolean) {
                SystemClock.sleep(1000);
                Log.e("1", "当前数据已经递增到---->" + count);
                count++;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mBoolean=false;
    }

    protected class MyBinder extends Binder {
        public MyIntentService2 mMyService;

        public MyBinder() {
            mMyService = MyIntentService2.this;
        }

        public int getCount() {
            return count;
        }

    }
    
}

源码

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.app;

import android.annotation.Nullable;
import android.annotation.WorkerThread;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

/**
 * IntentService is a base class for {@link Service}s that handle asynchronous
 * requests (expressed as {@link Intent}s) on demand.  Clients send requests
 * through {@link android.content.Context#startService(Intent)} calls; the
 * service is started as needed, handles each Intent in turn using a worker
 * thread, and stops itself when it runs out of work.
 *
 * <p>This "work queue processor" pattern is commonly used to offload tasks
 * from an application's main thread.  The IntentService class exists to
 * simplify this pattern and take care of the mechanics.  To use it, extend
 * IntentService and implement {@link #onHandleIntent(Intent)}.  IntentService
 * will receive the Intents, launch a worker thread, and stop the service as
 * appropriate.
 *
 * <p>All requests are handled on a single worker thread -- they may take as
 * long as necessary (and will not block the application's main loop), but
 * only one request will be processed at a time.
 *
 * <div class="special reference">
 * <h3>Developer Guides</h3>
 * <p>For a detailed discussion about how to create services, read the
 * <a href="{@docRoot}guide/components/services.html">Services</a> developer
 * guide.</p>
 * </div>
 *
 * @see android.support.v4.app.JobIntentService
 *
 * @deprecated IntentService is subject to all the
 *   <a href="/preview/features/background.html">background execution limits</a>
 *   imposed with Android 8.0 (API level 26). Consider using {@link androidx.work.WorkManager}
 *   or {@link androidx.core.app.JobIntentService}, which uses jobs
 *   instead of services when running on Android 8.0 or higher.
 */
@Deprecated
public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    @UnsupportedAppUsage
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * <p>If enabled is true,
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
     * {@link #onHandleIntent(Intent)} returns, the process will be restarted
     * and the intent redelivered.  If multiple Intents have been sent, only
     * the most recent one is guaranteed to be redelivered.
     *
     * <p>If enabled is false (the default),
     * {@link #onStartCommand(Intent, int, int)} will return
     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
     * dies along with it.
     */
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

    /**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null.
     * @see android.app.Service#onBind
     */
    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * This method is invoked on the worker thread with a request to process.
     * Only one Intent is processed at a time, but the processing happens on a
     * worker thread that runs independently from other application logic.
     * So, if this code takes a long time, it will hold up other requests to
     * the same IntentService, but it will not hold up anything else.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {@link #stopSelf}.
     *
     * @param intent The value passed to {@link
     *               android.content.Context#startService(Intent)}.
     *               This may be null if the service is being restarted after
     *               its process has gone away; see
     *               {@link android.app.Service#onStartCommand}
     *               for details.
     */
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值