问题
I've a service class (SaveMyAppsService.java
) in my project which once started will check for foreground application, if the current foreground application's package name matches with List<String> lockedApps
which holds the package names of locked Apps it should start another activity CustomPinActivity
but its not working!
PS: I'm able to see the mytag
logs in Logcat.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
lockedApps = AppPref.getInstance().getAppList(getApplicationContext());
String localPackName = checkRunningApps(); //returns package name of the current foreground app.
if( lockedApps.contains(localPackName) ){
Log.i("mytag","yes this is in lockedApps pref");
if( !allowedApps.contains( localPackName )){
Log.i("mytag","It was not allowed!!!!!!!!!!!!!!!!!!!!!!!!! but now it is");
allowedApps.add( localPackName );
previousAppName = localPackName;
Intent intent = new Intent(SaveMyAppsService.this.getApplicationContext(), CustomPinActivity.class);
intent.putExtra(AppLock.EXTRA_TYPE, AppLock.UNLOCK_PIN);
intent.putExtra("package",checkRunningApps());
startActivity( intent );
checkAllowed();
}
}
}
}, 0, 300, TimeUnit.MILLISECONDS);
回答1:
I think you should use Handler like this:
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
String localPackName = bundle.getString(AppLock.EXTRA_TYPE);
Intent intent = new Intent(SaveMyAppsService.this.getApplicationContext(), CustomPinActivity.class);
intent.putExtra(AppLock.EXTRA_TYPE, AppLock.UNLOCK_PIN);
intent.putExtra("package",localPackName);
startActivity( intent );
checkAllowed();
}
};
and your code updated :
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
lockedApps = AppPref.getInstance().getAppList(getApplicationContext());
String localPackName = checkRunningApps(); //returns package name of the current foreground app.
if( lockedApps.contains(localPackName) ){
Log.i("mytag","yes this is in lockedApps pref");
if( !allowedApps.contains( localPackName )){
Log.i("mytag","It was not allowed!!!!!!!!!!!!!!!!!!!!!!!!! but now it is");
allowedApps.add( localPackName );
previousAppName = localPackName;
Message msg = mHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString(AppLock.EXTRA_TYPE, localPackName);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
}
}
}, 0, 300, TimeUnit.MILLISECONDS);
来源:https://stackoverflow.com/questions/60474711/startactivity-not-working-inside-runnable-interface