032 Android Service

1.介绍

2.新建Service

(1)

(2)在Androidmanifest.xml文件中配置service

<service android:name=".Myservice"></service>

3.启动service

4.停止service

5.java后台

主界面

package com.lucky.test37service;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button1;
    Button button2;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=findViewById(R.id.button);
        button2=findViewById(R.id.button2);
        intent=new Intent(MainActivity.this,Myservice.class);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.putExtra("001","hello lucky"); //001为数据代号,"hello lucky"为传递的数据
                startService(intent); //可以通过intent传递数据
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });
    }
}

service

package com.lucky.test37service;

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

public class Myservice extends Service {

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

    //service创建时调用的方法
    @Override
    public void onCreate() {
        super.onCreate();
        flag1=true;
        Log.i("<<----------------->>","创建service");//在Logcat中可以看到方法的使用效果
    }

    //service启动时调用的方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String str=intent.getStringExtra("001"); //利用intent获取数据
        Log.i("<<----------------->>",str);
        new Thread(){
            @Override
            public void run() {
                while (flag1){
                    Log.i("<<----------------->>","we win");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        return super.onStartCommand(intent, flags, startId);
    }

    //service关闭时调用的方法
    @Override
    public void onDestroy() {
        Log.i("<<----------------->>","关闭service");
        flag1=false;
        super.onDestroy();
    }
}
原文地址:https://www.cnblogs.com/luckyplj/p/10519665.html