0
我正在編寫一個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,它的onClick法屁( )在MainActivity中被調用:
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和相同的聲音。我後來可能想添加記錄自己聲音的選項,因此解決方案應該嘗試啓用對(將來)應用中所做設置的更改,以直接影響該小部件。
我在這方面有幾個問題:
- 如何訪問從控件的代碼應用程序的方法(因爲我不知道如何使一個非靜態調用)?
- 在後臺運行整個時間並由應用程序和小部件共享的服務會是一個好主意嗎? (因爲內存和能源問題?)
我知道,在我的情況下,這是不是真的很重要,但有一個'service'在後臺運行「吃掉」的資源,不是嗎?由於我在技術上只需要播放一些簡短的聲音,是否有一種更「資源高效」的方式可以在單擊按鈕時啓動服務並在幾秒鐘後關閉它? – J0hj0h
只需執行服務,它不會吃剩餘資源,並在需要時自行停止。你不會注意到這樣一個'巨大'的資源使用情況 – Sam