关于Android开发中推送消息通知推送消息到前台的问题

发布时间 2023-09-11 10:13:08作者: wanzg

为什么推送点击发送按钮之后没有消息进行发送?(以简单音乐播放器为例)

1. 前景
  • 创建了一个Activity : ForegroundServiceActivity.java
// 代码如下:
package com.app.custom.demo01;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.app.custom.R;
import com.app.custom.service.MusicService;
public class ForegroundServiceActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_song; // 声明一个编辑框对象
    private Button btn_send_service; // 声明一个对象按钮对象
    private boolean isPlaying = true; // 是否正在播放

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foreground_service);
        et_song = findViewById(R.id.et_song);
        btn_send_service = findViewById(R.id.btn_send_service);
        btn_send_service.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_send_service) {
            if (TextUtils.isEmpty(et_song.getText())) {
                Toast.makeText(this, "请填写歌曲名称", Toast.LENGTH_SHORT).show();
            } 
	    // 创建一个通往音乐服务的意图
            Intent intent = new Intent(this, MusicService.class);
            intent.putExtra("is_play", isPlaying); // 是否正在播放音乐
            intent.putExtra("song", et_song.getText().toString());
            btn_send_service.setText(isPlaying ? "暂停播放音乐" : "开始播放音乐");
            startService(intent); // / 启动音乐播放服务
            isPlaying = !isPlaying;
        }
    }
}
  • 创建了一个相关联的XML文件
<!--代码如下:-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="歌曲名称:"
            android:textColor="@color/black"
            android:textSize="17sp" />

        <EditText
            android:id="@+id/et_song"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:background="@drawable/editext_selector"
            android:hint="请填写歌曲名称"
            android:textColor="@color/black"
            android:textSize="17sp" />

    </LinearLayout>

    <Button
        android:id="@+id/btn_send_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="开始播放音乐"
        android:textColor="#000000"
        android:textSize="17sp" />
</LinearLayout>
  • 创建了一个音乐播放器的服务
package com.app.custom.service;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.app.custom.R;
import com.app.custom.demo01.MainActivity;
import java.util.Objects;

public class MusicService extends Service {
    private final IBinder mBinder = new LocalBinder(); //创建一个粘合剂对象
    private String mSong;
    private boolean isPlaying = true; // 是否正在播放
    private int mProcess = 0;
    public class LocalBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    private Handler mHandler = new Handler(Objects.requireNonNull(Looper.myLooper())); // 声明一个处理器对象
    // 定义一个音乐播放器
    private Runnable mPlay = new Runnable() {
        @Override
        public void run() {
            if (isPlaying) {
                if (mProcess < 100) {
                    mProcess += 2;
                    mHandler.postDelayed(this, 1000);
                } else {
                    mProcess = 100;
                }
            }
            sendNotify(MusicService.this, mSong, isPlaying, mProcess); // 发送前台通知
        }
    };

    private void sendNotify(Context ctx, String song, boolean isPlaying, int process) {
        String message = String.format("歌曲%s", isPlaying ? "正在播放" : "暂停播放");
        // 创建一个跳转到活动页面的意图
        Intent intent = new Intent(ctx, MainActivity.class);
        // 创建一个用于页面跳转的延迟意图
        PendingIntent clickIntent = PendingIntent.getActivity(ctx,
                R.string.app_name, intent, PendingIntent.FLAG_IMMUTABLE);
        // 创建一个通知消息的建造器
        Notification.Builder builder = new Notification.Builder(ctx);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new Notification.Builder(ctx, getString(R.string.app_name));
        }
        builder.setContentIntent(clickIntent)
                .setSmallIcon(R.drawable.tt_s)
                // 设置通知栏右边的大图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.tt))
                .setProgress(100, process, false) // 设置进度条于当前进度
                .setContentTitle(song)
                .setContentText(message);
        Notification notification = builder.build();
        startForeground(5, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isPlaying = intent.getBooleanExtra("is_play", true);
        mSong = intent.getStringExtra("song");
        mHandler.postDelayed(mPlay, 200);
        return START_STICKY;
    }
}
  • 页面效果如下:
    image
2. 问题解决
  1. 在AndroidManifest.xml文件中开启前台权限
 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  1. 在AndroidManifest.xml文件中注册Service组件
<service android:name=".service.MusicService"/>
<!--注意:.service.MusicService是个人创建的包名-->

PS:可以直接在包处右键new一个service,这样AS会为我们自动创建一个已经注册好了的service

3. 本人问题所在

!!!手动创建了一个service,但是忘记注册了,还洋洋自得,气死了