是否有办法执行一个服务(启动或停止)只有当一个特定的应用程序是打开的?情况是,我有一个"泡沫"服务(类似于facebook),我只想在打开游戏Minecraft PE时出现。当我改变或我打开另一个应用程序,我想把隐形泡沫。这可能吗?
使用此代码
public class CheckRunningApplicationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context aContext, Intent anIntent) {
try {
ActivityManager am = (ActivityManager) aContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> alltasks = am
.getRunningTasks(1);
for (ActivityManager.RunningTaskInfo aTask : alltasks) {
if (aTask.topActivity.getClassName().equals("com.android.phone.InCallScreen")
|| aTask.topActivity.getClassName().equals("com.android.contacts.DialtactsActivity"))
{
Toast.makeText(aContext, "Phone Call Screen.", Toast.LENGTH_LONG).show();
}
String packageName = "com.example.checkcurrentrunningapplication";
if (aTask.topActivity.getClassName().equals(
packageName + ".Main"))
{
// When opens this example screen then show a alert message
Toast.makeText(aContext, "Check Current Running Application Example Screen.",
Toast.LENGTH_LONG).show();
}
}
} catch (Throwable t) {
Log.i("THROW", "Throwable caught: "
+ t.getMessage(), t);
}
}
}
将此添加到Manifest:
<receiver android:name = ".CheckRunningApplicationReceiver"/>
<uses-permission android:name="android.permission.GET_TASKS" />