VAV0 2022-05-09 22:08 采纳率: 100%
浏览 76
已结题

Android studio中的widget和service实现音乐桌面控件

appwidget_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#00BCD4"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/play"
        android:layout_width="57dp"
        android:layout_height="match_parent"
        android:src="@android:drawable/ic_media_play"></ImageView>

    <ImageView
        android:id="@+id/stop"
        android:layout_width="73dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="50dp"
        android:src="@android:drawable/ic_media_pause"></ImageView>

</LinearLayout>

Appwidget.java

package com.example.myapplication;


import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class AppWidget extends AppWidgetProvider {

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
         Log.d(this.getClass().getName(), "onReceive");

        if (intent == null)
            return;

        String action = intent.getAction();

        // 停止播放
        if (action.equals(Constants.ACTION_STOP)) {
            Intent serviceIntent = new Intent(context, MyService.class);
            context.stopService(serviceIntent);
        }

        // 点击了按钮,启动一个后台服务播放
        if (action.equals(Constants.ACTION_PLAY)) {
            String TAG="AAAA";
            Log.d(TAG, "aaaaa ");
            Intent serviceIntent = new Intent(context, MyService.class);
            context.startService(serviceIntent);
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Log.d(this.getClass().getName(), "onUpdate");

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget_layout);

        // 播放图片作为按钮,绑定播放事件
        Intent intentPlay = new Intent(Constants.ACTION_PLAY);
        PendingIntent pendingIntentPlay = PendingIntent.getBroadcast(context, Constants.REQUEST_CODE_PLAY, intentPlay,
                PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.play, pendingIntentPlay);

        // 停止图片作为按钮,绑定停止事件
        Intent intentStop = new Intent(Constants.ACTION_STOP);
        PendingIntent pendingIntentStop = PendingIntent.getBroadcast(context, Constants.REQUEST_CODE_STOP, intentStop,
                PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.stop, pendingIntentStop);

        // 更新AppWidget
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

    /**
     * 删除AppWidget
     */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
        Log.d(this.getClass().getName(), "onDeleted");
    }

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
        Log.d(this.getClass().getName(), "onDisabled");
    }

    /**
     * AppWidget首次创建调用
     */
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        Log.d(this.getClass().getName(), "onEnabled");
    }
}

MyService.java

package com.example.myapplication;

import java.io.File;

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

public class MyService extends Service {

    // 播放器
    private MediaPlayer mMediaPlayer;

    // 音频文件
    File audioFile;

    @Override
    public void onCreate() {
        super.onCreate();

        mMediaPlayer = new MediaPlayer();

        // 根目录
        File sdcard = Environment.getExternalStorageDirectory();
        audioFile = new File(sdcard, "th.mp3");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 重置
        mMediaPlayer.reset();

        // 设置播放器的声音源
        try {
            mMediaPlayer.setDataSource(audioFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 也可以从一个静态资源文件中加载音频数据源
         mMediaPlayer.create(this, R.raw.th);

        if (!mMediaPlayer.isPlaying()) {
            try {
                mMediaPlayer.prepare();
            } catch (Exception e) {
                e.printStackTrace();
            }

            mMediaPlayer.start();

            // 如果设置循环true,那么将循环播放
             mMediaPlayer.setLooping(true);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

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

Constants.java

package com.example.myapplication;

public class Constants {
    public static final String ACTION_PLAY = "action_play";
    public static final String ACTION_STOP = "action_stop";
    public static final int REQUEST_CODE_PLAY = 0xd05;
    public static final int REQUEST_CODE_STOP = 0xd06;
}

AndroidManifest.xml

<?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">
        <receiver android:name="com.example.myapplication.AppWidget"
            android:exported="true">

            <intent-filter>
                <action android:name="action_play" />
            </intent-filter>

            <intent-filter>
                <action android:name="action_stop" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/appwidget" />

        </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>
        <service android:name="com.example.myapplication.MyService"
            android:enabled="true"
            android:exported="true">
        </service>
    </application>

</manifest>

但是我的控件点击了没有反应

  • 写回答

1条回答 默认 最新

  • 不会写代码的猴子 Android领域优质创作者 2022-05-10 09:24
    关注

    断点跟踪看看是不是触发了事件

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月18日
  • 已采纳回答 5月10日
  • 创建了问题 5月9日

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题