5.21

所花时间(包括上课):2

打码量(行):150

博客量(篇):1

了解到知识点:学习Service

 

 package com.example.myapp;

 

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.util.Log;

 

public class MyService extends Service {

 

    private static final String TAG = "MyService";

 

    @Override

    public void onCreate() {

        super.onCreate();

        Log.d(TAG, "onCreate: Service created");

    }

 

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "onStartCommand: Service started");

        // 在此处处理后台任务逻辑

        return START_STICKY; // 如果服务因内存不足而被杀死,系统会尝试重新创建服务

    }

 

    @Override

    public IBinder onBind(Intent intent) {

        // 如果不需要绑定,则返回 null

        return null;

    }

 

    @Override

    public void onDestroy() {

        super.onDestroy();

        Log.d(TAG, "onDestroy: Service destroyed");

    }

}

package com.example.myapp;

 

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

 

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

 

    public void startService(View view) {

        Intent serviceIntent = new Intent(this, MyService.class);

        startService(serviceIntent);

    }

 

    public void stopService(View view) {

        Intent serviceIntent = new Intent(this, MyService.class);

        stopService(serviceIntent);

    }

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

 

    <Button

        android:id="@+id/startServiceButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Start Service"

        android:onClick="startService"

        android:layout_centerInParent="true" />

 

    <Button

        android:id="@+id/stopServiceButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Stop Service"

        android:onClick="stopService"

        android:layout_below="@id/startServiceButton"

        android:layout_marginTop="16dp"

        android:layout_centerHorizontal="true" />

 

</RelativeLayout>

posted @ 2024-05-21 21:16  赵千万  阅读(6)  评论(0编辑  收藏  举报