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 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败