我正在启动一项服务,该服务会检测用户何时启动应用程序并显示带有应用程序名称的Toast。
package com.xylon.serviceexample;
import java.util.List;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
for (int i = 0; i < runningAppProcessInfo.size(); i++) {
Log.v("Proc: ", runningAppProcessInfo.get(i).processName);
Toast.makeText(this, runningAppProcessInfo.get(i).processName, Toast.LENGTH_LONG).show();
}
Log.d(TAG, "onStart");
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
}
我是否将ActivityManager代码放在正确的位置?它显示了服务启动时已在设备上运行的应用程序。
答案 0 :(得分:0)
您可以使用READ LOGS执行此操作,然后从logcat跟踪..
在清单文件中添加:
android.permission.READ_LOGS
代码:
try
{
Process mLogcatProc = null;
BufferedReader reader = null;
mLogcatProc = Runtime.getRuntime().exec(new String[]{"logcat", "-d"});
reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));
String line;
final StringBuilder log = new StringBuilder();
String separator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
String w = log.toString();
Toast.makeText(getApplicationContext(),w, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
但是从API 16开始,google限制了这个东西,所以现在我们无法追踪这个东西。