我正在实施以下服务来播放声音。当有人按下任何菜单按钮时,此声音停止。但如果我按下设备声音的主页键还在播放。我正在添加此代码
@Override
protected void onPause() {
super.onPause();
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
}
在我的活动课上。但仍然听起来不停。为什么onPause方法不起作用?
服务代码 -
public class PlayAudio extends Service{
private static final String LOGCAT = null;
MediaPlayer objPlayer;
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this, R.raw.test);
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.stop();
objPlayer.release();
}
public void onPause(){
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
@Override
public IBinder onBind(Intent objIndent) {
return null;
}
}
答案 0 :(得分:0)
你可以停止按下主页上的服务..这个
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
}
});
答案 1 :(得分:0)
在Thread
中写一个Service
,它会不断检查正在运行的任务,并停止Service
个顶级任务到活动包名称等于启动器应用程序的包名... < / p>
new Thread() {
public void run() {
final List<ResolveInfo> activities = getPackageManager().queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
final ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
while(true) {
String packageName = activityManager.getRunningTasks(5).get(0).topActivity.getPackageName();
if(activities.contains(packageName)) {
break;
}
try {
Thread.sleep(500); // wait for half second
} catch (InterruptedException e) {
}
}
stopSelf();
};
}.start();