service应用

service

开发service的两步
  创建service子类
  在清单文件中配置

创建服务

service启动与停止

startServie()方法:访问者与service之间没有关联 退出也在运行
bindService()方法:访问者与service绑定在一起,访问者退出,service终止

startService启动与关闭

bind启动

service的生命周期
satrservice方式

先执行onCreate()方法--再执行onStatrtCommand()


##strings
<resources>
    <string name="app_name">My Application</string>
    <string name="msg">后台播放音乐</string>
    <string name="beginCaption">开始</string>
    <string name="endCaption">结束</string>
</resources>

###Myservice  在java目录下创建 和MainActivity同目录

package com.example.myapplication;

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

import java.security.Provider;

public abstract class MyService extends Service {
    //为日志工具设置标签
    private static String TAG = "MyService";
    //定义音乐播放器变量
    private MediaPlayer mediaPlayer;
    @Override
    public void onCreate(){
        Toast.makeText(this,"MyService onCreate()",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MyService onCreate()");
        mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.korea_jiangnanstyle);
        //设置可以重复播放
        mediaPlayer.setLooping(true);
        super.onCreate();


    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Toast.makeText(this,"MyService onStart()",Toast.LENGTH_SHORT).show();Log.e(TAG,"MyService onStatr()");
        mediaPlayer.start();
//        Intent intent;
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy(){
        Toast.makeText(this,"MyService onDestroy()",Toast.LENGTH_SHORT).show();Log.e(TAG,"MyService onDestroy()");
        mediaPlayer.stop();
        super.onDestroy();
    }
    @Override
    public IBinder onBind(Intent intent){
        return null;
    }
}

###放入音乐文件
###在res下创建文件夹raw并把音乐文件上传

###MainActivity

package com.example.myapplication;

import android.app.AppComponentFactory;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    //为日志工具设置标签
    private static String TAG = "MyService";
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //输出Toast消息和日志记录
        Toast.makeText(this,"MyServiceActivity",Toast.LENGTH_SHORT).show();
        Log.e(TAG,"MyServiceActivity");
        initlizeViews();
    }

    private void initlizeViews() {
        Button btnStart = (Button) findViewById(R.id.btn_begin);
        Button btnStop = (Button) findViewById(R.id.btn_end);
        
        //定义单击事件监听器
        View.OnClickListener ocl = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //显示指定intent所指的对象是服务
                Intent intent = new Intent(MainActivity.this,MyService.class);
                switch (view.getId()){
                    case R.id.btn_begin:
                        //开始服务
                        startService(intent);
                        break;
                    case R.id.btn_end:
                        //停止服务
                        stopService(intent);
                        break;
                }
            }
        };
        //绑定单机事件监听器
        btnStart.setOnClickListener(ocl);
        btnStop.setOnClickListener(ocl);
    }
}

//activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/msg" />

    <Button
        android:id="@+id/btn_begin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/beginCaption" />

    <Button
        android:id="@+id/btn_end"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/endCaption" />
</LinearLayout>
###AndroidMainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:enabled="true" android:name=".MyService"/>
    </application>

</manifest>

posted @ 2023-05-23 11:03  idazhi  阅读(15)  评论(0编辑  收藏  举报