About three startup methods of Service (1)

First of all, no matter which startup method is used, the Service needs to be registered in the manifest configuration file.

Explain these three ways with an example: display system time, time from service

The first boot mode:

Build a MyService class, inherit from Service and
build a Handler
to send a broadcast every 1 second in the onCreate method. The data in the broadcast is the current time. The code is as follows:

handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO 发送广播
                Intent intent=new Intent("com.zph");
                intent.putExtra("time", getServiceTime());
                sendBroadcast(intent);
                handler.postDelayed(this, 1000);
            }
        }, 1000);

Of course, we also need a broadcast receiver, and a class is built in MainActivity. The
code is as follows:

public class MyReceive extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.zph".equals(intent.getAction())){
                tv.setText(intent.getStringExtra("time"));
            }
        }
    }

The last thing is to register for its broadcast

IntentFilter filter=new IntentFilter();
filter.addAction("com.zph");
registerReceiver(receiver, filter);

But don't forget to unregister.
Then we can start and stop the service through two buttons, and then we broadcast the receiver to get the data and display it on our TextView

//开启服务
Intent intent=new Intent(this,MyService.class);
startService(intent);
//停止服务
Intent intent=new Intent(this,MyService.class);
stopService(intent);

Don't forget to close the handler object in the OnDestroy method in MyService

handler.removeCallbacksAndMessages(null);//传null是全都取消

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325392291&siteId=291194637