我正在编写一个fartbutton应用程序和小部件。小部件应该使用完全相同的方法来播放屁声。
在主应用中,在MainActivity.java的 onCreate()中调用以下方法:
public void initializeSoundPool() {
// Initialize SoundPool:
setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
String[] soundArray = new String[1];
// Saving all sounds' names:
try {
soundArray = this.getAssets().list("fartSounds");
} catch (IOException e) {
e.printStackTrace();
}
// Loading all sounds into SoundPool:
soundCount = soundArray.length;
soundCollection = new int[soundCount];
for (int i = 0; i < soundCount; i++) {
try {
soundCollection[i] = soundPool.load(this.getAssets().openFd("fartSounds/" + soundArray[i]), 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
当用户按下(仅)ImageButton时,会调用MainActivity中的onClick方法 fart():
public void fart(View view) {
// Randomize sample and frequency:
Random random = new Random();
int randomNumber = random.nextInt(soundCount);
while (randomNumber == lastPlayed) {
randomNumber = random.nextInt(soundCount);
}
int currentSound = soundCollection[randomNumber];
float frq = random.nextFloat() + 1f;
// Play selected sound with selected frequency:
soundPool.play(currentSound, 1f, 1f, 0, 0, frq);
// Save the sound's number for next time a sound should play:
lastPlayed = randomNumber;
}
对于小部件,我终于找到了一种方法来点击:
public class FurzknopfWidgetProvider extends AppWidgetProvider {
private static final String ACTION_CLICK = "fart";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
ComponentName thisWidget = new ComponentName(context, FurzknopfWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent intent = new Intent(context, FurzknopfWidgetProvider.class);
intent.setAction(ACTION_CLICK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.widgetFartButton, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ACTION_CLICK)) {
Log.d("Widget", "FART!");
}
}
}
由于小部件基本上与应用程序完全相同,我想使用相同的soundpool和相同的声音。我后来可能想添加录制自己声音的选项,因此解决方案应该尝试对(未来)应用中的设置进行更改以直接影响窗口小部件。
我在这方面有几个问题:
答案 0 :(得分:0)
我建议您使用Service
来管理所有音乐操作(播放,初始化等)&amp;通过Intents处理所有通信。
有一个AOSP project显示(MusicService类)