如何允许应用和小组件"share"方法



我正在编程一个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!");
}
}
}

由于这个小部件基本上和应用程序完全一样,我想使用相同的声音池和相同的声音。我稍后可能想添加录制自己声音的选项,因此解决方案应该尝试启用对(未来)应用程序中的设置的更改,以直接影响小部件。

在这方面,我有几个问题:

  • 如何从小部件的代码访问应用程序的方法(因为我不知道如何进行非静态调用)
  • 一个始终在后台运行并由应用程序和小部件共享的服务是个好主意吗?(因为记忆力和精力问题?)

我建议您使用Service来管理所有音乐操作(播放、初始化等)&通过Intents处理所有通信。

有一个AOSP项目显示(MusicService类)

相关内容

最新更新