对于Listen类型,方法getSystemService(String)是未定义的

时间:2011-08-05 23:14:53

标签: android

我正在尝试检查com.android.music是否正在运行,我在此行this.getSystemService(Context.ACTIVITY_SERVICE);

上收到以下错误

错误:

  

对于类型Listen

,方法getSystemService(String)未定义

代码:

public boolean isMusicRunning() {        
    ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    for (int i = 0; i < procInfos.size(); i++) {
        if (procInfos.get(i).processName.equals("com.android.music")) {
            Toast.makeText(null, "music is running",
                    Toast.LENGTH_LONG).show();
        }
    }
}

如果你能让我知道我在这里做错了什么就会很棒!

3 个答案:

答案 0 :(得分:58)

getSystemService是类Context的方法,因此您需要在上下文中运行它。

您复制它的原始代码可能是从Activity派生类运行的。如果它不在Activity中,你需要将Context参数传递给你的方法。

答案 1 :(得分:22)

你应该这样使用:

public boolean isMusicRunning(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    for (int i = 0; i < procInfos.size(); i++) {
        if (procInfos.get(i).processName.equals("com.android.music")) {
            Toast.makeText(null, "music is running", Toast.LENGTH_LONG).show();
        }
    }
} 

答案 2 :(得分:1)

答案都是正确的,但没有人指出解决问题的正确方法。

  

您应该使用广播接收器来获取当前播放的歌曲。

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        String cmd = intent.getStringExtra("command");
        Log.v("tag ", action + " / " + cmd);
        String artist = intent.getStringExtra("artist");
        String album = intent.getStringExtra("album");
        String track = intent.getStringExtra("track");
        Log.v("tag", artist + ":" + album + ":" + track);
        Toast.makeText(CurrentMusicTrackInfoActivity.this, track, Toast.LENGTH_SHORT).show();
    }
};

并将其添加到“创建”

IntentFilter iF = new IntentFilter();

iF.addAction("com.android.music.metachanged");
iF.addAction("com.htc.music.metachanged");

iF.addAction("fm.last.android.metachanged");
iF.addAction("com.sec.android.app.music.metachanged");
iF.addAction("com.nullsoft.winamp.metachanged");
iF.addAction("com.amazon.mp3.metachanged");     
iF.addAction("com.miui.player.metachanged");        
iF.addAction("com.real.IMP.metachanged");
iF.addAction("com.sonyericsson.music.metachanged");
iF.addAction("com.rdio.android.metachanged");
iF.addAction("com.samsung.sec.android.MusicPlayer.metachanged");
iF.addAction("com.andrew.apollo.metachanged");
registerReceiver(mReceiver, iF);

另请查看this

123 abc的更好答案

简单检查音乐是否正在播放。使用

AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())//it checks whether music is played by Android OS
 {
     // Something is being played.
 }