android 一分钟理解service原理

这是一个计时功能的service,可以看出来不论当前界面时怎样的,该service一直在后台运行。

“开始service”和“结束service”两个按钮分别控制service的开始和结束。

代码部分:

复写四个函数:

1.onbind

package com.example.administrator.model.ServiceDemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.example.administrator.model.MainActivity;

import java.util.Timer;
import java.util.TimerTask;

public class SimpleService extends Service {
    String TAG = "test service";
    private int count;
    Timer timer;
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return null;
    }

    @Override
    public void onCreate() {//首次创建时调用
        Log.d(TAG, "onCreate: ");
        super.onCreate();
        timer = new Timer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {//每次start service时调用
        Log.d(TAG, "onStartCommand: ");
        Toast.makeText(getApplicationContext(),"service start", Toast.LENGTH_LONG).show();
        count = intent.getIntExtra("count",MainActivity.count);
        count();
        return super.onStartCommand(intent, flags, startId);
    }

    public void count(){
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Intent counter = new Intent();
                counter.putExtra("count",count);
                counter.setAction("countAction");
                sendBroadcast(counter);
                count++;
                Log.d("xjx","count = "+count);
            }
        },0,1000);
    }

    @Override
    public void onDestroy() {//关闭服务时调用
        Log.d(TAG, "onDestroy: ");
        super.onDestroy();
        timer.cancel();
        Toast.makeText(getApplicationContext(),"service stop", Toast.LENGTH_LONG).show();
    }
}

两个按钮的控制代码:

        Button button10 = findViewById(R.id.button10);
        button10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(context,"here",Toast.LENGTH_LONG).show();
                //if(count!=0){
                    count = Integer.valueOf(serviceWindow.getText().toString()).intValue();
                //}
                intent.putExtra("count","count");
                startService(intent);
                Log.d("xjx","send service message");
            }
        });

        Button button11 = findViewById(R.id.button11);
        button11.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(context,"here",Toast.LENGTH_LONG).show();
                //Intent intent = new Intent(MainActivity.this,SimpleService.class);
                stopService(intent);
            }
        });

 

你可能感兴趣的:(android 一分钟理解service原理)