Android Studio广播实验

#基于service基础上实现

AndroidManfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyService"
        tools:targetApi="31">
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
        <receiver
            android:name=".MyBroadcastReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="MusicReceiver.ACTION" />
            </intent-filter>
        </receiver>

        <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>
    </application>

</manifest>

 activity_xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@drawable/chinabirthday"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/palyer"
        android:layout_width="214dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="550dp"
        android:src="@drawable/player"
        android:scaleType="centerInside"
        />
    <Button
        android:id="@+id/stop"
        android:layout_width="150dp"
        android:layout_height="100dp"
        android:layout_marginTop="200dp"
        android:text="停止"
        android:textSize="30sp"></Button>

</RelativeLayout>

 MainActivity

 

package com.example.myservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public   class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(MainActivity.this, MyService.class);
        ImageButton btn_play = (ImageButton) findViewById(R.id.palyer);
        Button bt_stop =findViewById(R.id.stop);
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent11 = new Intent();
                intent11.setAction(MyBroadcastReceiver.ACTION);
                intent11.setPackage(getPackageName());
                //启动和停止MusicService
                if(MyService.isplay == false){
                    startService(intent);//启动Sevice
                    intent11.putExtra(MyBroadcastReceiver.ACTION_KEY,MyBroadcastReceiver.ACTION_PLAY);
                }
                else{
                    intent11.putExtra(MyBroadcastReceiver.ACTION_KEY,MyBroadcastReceiver.ACTION_PAUSE);//放在前面放在后面service停止就无法执行了
                    stopService(intent);//停止Service
                }
                sendBroadcast(intent11);
            }
        });
        //发送广播
        bt_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //第一步,创建intent对象,且设置intent对象的Action属性,相当于一个暗号,还要指定带启动组件的包名和类名
                Intent intent1 = new Intent();
                //使用静态注册
                intent1.setAction(MyBroadcastReceiver.ACTION);
                intent1.setPackage(getPackageName());
                //第二步:编写需要广播信息的内容,将广播的信息封装到intent对象中
                int id =view.getId();
                if (id == R.id.palyer){
                    intent1.putExtra(MyBroadcastReceiver.ACTION_KEY,MyBroadcastReceiver.ACTION_PLAY);
                } else if (id == R.id.stop) {
                    intent1.putExtra(MyBroadcastReceiver.ACTION_KEY,MyBroadcastReceiver.ACTION_PAUSE);
                }

//                switch (view.getId()) {//Views使用switch
//                    case R.id.player:
//                        intent1.putExtra(MyBroadcastReceiver.ACTION_KEY,MyBroadcastReceiver.ACTION_PLAY);
//                        break;
//                    case R.id.stop:
//                        intent1.putExtra(MyBroadcastReceiver.ACTION_KEY,MyBroadcastReceiver.ACTION_PAUSE);
//                        break;
//                }
                //第三步:通过sendBroadcast方法将广播发送出去
                sendBroadcast(intent1);
            }
        });
    }
}

MyBroadcastReceiver

package com.example.myservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Switch;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
    /*
    需要这几个变量
    1.action,key;
    2。paly,pause
     */
    public  static  final  String ACTION  ="MusicReceiver.ACTION";
    public  static  final  String ACTION_KEY  ="action_type";
    public  static  final  String ACTION_PLAY  ="play";
    public  static  final  String ACTION_PAUSE  ="pause";

    @Override
    public void onReceive(Context context, Intent intent) {
        //1.接收到的广播内容,给actiontype接收
        String actionType = intent.getStringExtra(ACTION_KEY);
        //第二步:编写接收到广播后的响应动作
        if (actionType != null){//判断空很重要,避免空指针
            Intent serviceintent =new Intent(context, MyService.class);
            //遇到了自己使用swit语句出错,写一个系统自带的
            switch (actionType) {//Views使用switch
                case MyBroadcastReceiver.ACTION_PLAY:
                    context.startService(serviceintent);
                    Toast.makeText(context,"静态注册:接收到播放广播",Toast.LENGTH_LONG).show();
                    break;
                case MyBroadcastReceiver.ACTION_PAUSE :
                    if (MyService.isplay){
                        context.stopService(serviceintent);
                        Toast.makeText(context,"静态注册:接收到暂停广播",Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    }
}

MyService

package com.example.myservice;

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

public class MyService extends Service {
    //设置连个变量,跟别记录当前播放状态的,播放器对象
    static boolean isplay;
    MediaPlayer player;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
//        Log.i("Service","Service已创建");
        player =MediaPlayer.create(this,R.raw.lovechina);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!player.isPlaying()){
            player.start();//播放音乐
             isplay = player.isPlaying();//设置当前状态为正在播放
        }
//        Log.d(TAG,"onStartCommand:-----onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        player.stop();//停止音乐的播放
        isplay =player.isPlaying();//当前状态为停止播放
        player.release();//释放资源
//        Log.i("Service","Service已停止");
        super.onDestroy();
    }
}

android目录

目录中的drawable文件为自己的素材,大家使用时,自己在网上找一个即可。

本代码可实现service和广播。

  • 17
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值