在activity中启动service,通过Handler在se

2019-03-06  本文已影响0人  大道至简_知易行难
360截图20190306173441255.jpg

1、首先注册service 通过start的方式启动service

/**
 * 测试通过startService启动service的执行情况
 *
 * @author SuTongsheng
 * @create 2019/3/6
 * @Describe
 */
public class StartService extends Service {
    private static final String TAG = "StartService";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate: ");

        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        new MyThread().start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: ");
        super.onDestroy();
    }

    private class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(100);
                    Message message = new Message();
                    message.what = i;
                    ServiceActivity.serviceHandler.sendMessage(message);
                    Log.i(TAG, "run: " + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            super.run();
        }
    }

}

2、创建acitivity,其中点击按钮启动service并打印数字,StartService中通过引用ServiceActivity中的handler发送数字num。activity中通过Handler接收并显示在TextView上

 private void initView() {
        serviceHandler = new ServiceHandler();

        tv_show_service_num = this.findViewById(R.id.tv_show_service_num);
        this.findViewById(R.id.bt_start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService();
            }
        });
    }

    public class ServiceHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != 0) {
                int num = msg.what;
                tv_show_service_num.setText(num + "");
            }
            super.handleMessage(msg);
        }
    }

    private void startService() {
        startIntent = new Intent(this, StartService.class);
        startService(startIntent);

    }
上一篇下一篇

猜你喜欢

热点阅读