在activity中启动service,通过Handler在service中打印1-99显示在acticity中

在activity中启动service,通过Handler在service中打印1-99显示在acticity中_第1张图片
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);

    }

你可能感兴趣的:(在activity中启动service,通过Handler在service中打印1-99显示在acticity中)