我正在尝试构建一个应用程序,我的应用程序在后台运行,并检测用户何时启动任何其他应用程序。
例如,如果用户启动Google Play商店,那么我想展示Toast" Google Play应用已推出"
以下是我所关注的SO链接:https://stackoverflow.com/a/11346800
每当我点击任何应用程序时,例如:Google Play应用程序或Gmail应用程序或任何其他应用程序。我没有收到任何Toast消息,说明" APPNAME应用程序已启动"
我在代码中遗漏的内容,以下是我的服务类的完整代码:
public class NotifyService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++) {
long endTime = System.currentTimeMillis() + 10 * 1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
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) {
}
}
}
Log.d("ServiceRunning:", "Service Running");
}
stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(MainActivity.this, NotifyService.class));
}
}