我有一個應用程序,它具有啓動應用程序,潘多拉電臺或快捷方式的功能。這一切都很好。後來我想停止我開始的應用程序。這適用於除Pandora和Spotify之外的大多數情況,並不總是關閉。有時他們會但不總是。這似乎與當前的用戶界面狀態有關。例如,當我有Pandora顯示或主屏幕顯示時,它工作正常。當Home Dock或Car Mode激活時,它不起作用。您可以在這裏看到我所有的源代碼:http://code.google.com/p/a2dpvolume/ service.java是具有此功能的文件。如何停止或暫停Pandora和Spotify
這是試圖阻止音樂播放,然後停止應用程序的代碼的一部分。
if (bt2.hasIntent()) {
// if music is playing, pause it
if (am2.isMusicActive()) {
// first pause the music so it removes the notify icon
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
sendBroadcast(i);
// for more stubborn players, try this too...
Intent downIntent2 = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent downEvent2 = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP);
downIntent2.putExtra(Intent.EXTRA_KEY_EVENT, downEvent2);
sendOrderedBroadcast(downIntent2, null);
}
// if we opened a package for this device, try to close it now
if (bt2.getPname().length() > 3 && bt2.isAppkill()) {
// also open the home screen to make music app revert to
// background
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
// now we can kill the app is asked to
final String kpackage = bt2.getPname();
CountDownTimer killTimer = new CountDownTimer(6000, 3000) {
@Override
public void onFinish() {
try {
stopApp(kpackage);
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG, "Error " + e.getMessage());
}
}
@Override
public void onTick(long arg0) {
if (am2.isMusicActive()) {
// for more stubborn players, try this too...
Intent downIntent2 = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
KeyEvent downEvent2 = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP);
downIntent2.putExtra(Intent.EXTRA_KEY_EVENT, downEvent2);
sendOrderedBroadcast(downIntent2, null);
}
try {
stopApp(kpackage);
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG, "Error " + e.getMessage());
}
}
};
killTimer.start();
}
}
這裏是函數stopApp()。
protected void stopApp(String packageName) {
Intent mIntent = getPackageManager().getLaunchIntentForPackage(
packageName);
if (mIntent != null) {
try {
ActivityManager act1 = (ActivityManager) this
.getSystemService(ACTIVITY_SERVICE);
// act1.restartPackage(packageName);
act1.killBackgroundProcesses(packageName);
List<ActivityManager.RunningAppProcessInfo> processes;
processes = act1.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo info : processes) {
for (int i = 0; i < info.pkgList.length; i++) {
if (info.pkgList[i].contains(packageName)) {
android.os.Process.killProcess(info.pid);
}
}
}
} catch (ActivityNotFoundException err) {
err.printStackTrace();
Toast t = Toast.makeText(getApplicationContext(),
R.string.app_not_found, Toast.LENGTH_SHORT);
if (notify)
t.show();
}
}
}
有其他人遇到這個問題嗎?我如何可靠地停止啓動的應用程序?我需要先暫停並放入後臺。這是我遇到的問題。它適用於大多數情況,但不是全部。有些情況下,Pandora和Spotify不會響應正在發送的關鍵事件,而只是繼續播放。這使通知圖標保持活動狀態,並使應用程序成爲前臺活動,所以我無法阻止它。