为此,首先我从堆栈中获取顶级活动,然后在logcat中匹配Facebook的字符串。 我正在使用此代码,
public class MyService extends Service
{
public static String Tag = "Task";
public static String Tag1 = "Top Running Task";
ActivityManager am ;
String packageName ;
Handler handler;
int count=0;
@Override
public int onStartCommand(Intent intent,int flags, int startId)
{
// TODO Auto-generated method stub
super.onStartCommand(intent, flags,startId);
Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();
handler = new Handler(){
@Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
super.handleMessage(msg);
// Browser.clearHistory(getContentResolver());
//Browser.clearSearches(getContentResolver());
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
if((packageName).indexOf("browser")!= -1)
{
// Toast tost=Toast.makeText(getApplicationContext(), packageName.toString(), 1);
//tost.show();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
if(line.contains("facebook.com"))
{
//Browser.addSearchUrl(getContentResolver(), "google");
Log.i(Tag1,"ww"+ line);
/*Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);*/
//android.os.Process.killProcess(pid);
}
//log.;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//}
}
};
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
handler.sendEmptyMessage(0);
}
catch (InterruptedException e) {}
}
}
}).start();
return START_NOT_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
am.killBackgroundProcesses(packageName);
Log.i(Tag,"destory ");
}
@Override
public IBinder onBind(Intent intent)
{
//TODO for communication return IBinder implementation
return null;
}
}
我正在删除历史记录和缓存。 在那之后,我能够阻止Facebook,但第一次,它工作正常,但第二次它不起作用,它保持其历史5-6秒,然后再次工作正常。