How to programmatically get launch time of other apps in android? - android

I want to get launch time of all apps in android. Please suggest me any solution to achieve this. I am using this code. It is to kill non system apps. But it is also not working. Can anybody suggest any solution for it. Thanks
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
List<RunningAppProcessInfo> appProcesses= activityManager.getRunningAppProcesses();
for (RunningAppProcessInfo appProcess : appProcesses) {
try {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
if (!lastFrontAppPkg.equals((String) appProcess.pkgList[0])) {
apkInfo = ApkInfo.getInfoFromPackageName(appProcess.pkgList[0], mContext);
if (apkInfo == null || (apkInfo.getP().applicationInfo.flags && ApplicationInfo.FLAG_SYSTEM) == 1) {
// System app continue;
} else if (((apkInfo.getP().versionName == null)) || (apkInfo.getP().requestedPermissions == null)) {
//Application that comes preloaded with the device
continue;
} else {
lastFrontAppPkg = (String) appProcess.pkgList[0];
}
//kill the app
//Here do the pupop with password to launch the lastFrontAppPkg if the pass is correct
}
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}, 0, 1000);

Related

A bug of AccessibilityManagerService

Bug Des:
a variable mBindingSerivce in UserState.java has not cleared after fail start Accessibility Service
mBindingSerivce means a Accessibility Service set of being started
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
synchronized (mLock) {
if (mService != service) {
if (mService != null) {
mService.unlinkToDeath(this, 0);
}
mService = service;
try {
// start Accessibility Service
mService.linkToDeath(this, 0);
} catch (RemoteException re) {
// fail start Accessibility Service, will run binderDied()
Slog.e(LOG_TAG, "Failed registering death link");
binderDied();
// will directly return
return;
}
}
mServiceInterface = IAccessibilityServiceClient.Stub.asInterface(service);
UserState userState = mUserStateWeakReference.get();
if (userState == null) return;
userState.addServiceLocked(this);
mSystemSupport.onClientChangeLocked(false);
// Initialize the service on the main handler after we're done setting up for
// the new configuration (for example, initializing the input filter).
mMainHandler.sendMessage(obtainMessage(
AccessibilityServiceConnection::initializeService, this));
}
}
public void binderDied() {
synchronized (mLock) {
// It is possible that this service's package was force stopped during
// whose handling the death recipient is unlinked and still get a call
// on binderDied since the call was made before we unlink but was
// waiting on the lock we held during the force stop handling.
if (!isConnectedLocked()) {
return;
}
mWasConnectedAndDied = true;
UserState userState = mUserStateWeakReference.get();
if (userState != null) {
userState.serviceDisconnectedLocked(this);
}
resetLocked();
mSystemSupport.getMagnificationController().resetAllIfNeeded(mId);
mSystemSupport.onClientChangeLocked(false);
}
}
so when restart Service, the code will run. please see 1 comment.
private void updateServicesLocked(UserState userState) {
// ...
for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) {
AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i);
ComponentName componentName = ComponentName.unflattenFromString(
installedService.getId());
AccessibilityServiceConnection service = componentNameToServiceMap.get(componentName);
// Ignore non-encryption-aware services until user is unlocked
if (!isUnlockingOrUnlocked && !installedService.isDirectBootAware()) {
Slog.d(LOG_TAG, "Ignoring non-encryption-aware service " + componentName);
continue;
}
// 1. will run return due to mBindingService have not cleared
if (userState.mBindingServices.contains(componentName)) {
continue;
}
if (userState.mEnabledServices.contains(componentName)
&& !mUiAutomationManager.suppressingAccessibilityServicesLocked()) {
if (service == null) {
service = new AccessibilityServiceConnection(userState, mContext, componentName,
installedService, sIdCounter++, mMainHandler, mLock, mSecurityPolicy,
this, mWindowManagerService, mGlobalActionPerformer);
} else if (userState.mBoundServices.contains(service)) {
continue;
}
service.bindLocked();
} else {
if (service != null) {
service.unbindLocked();
}
}
}
//...
}
this will cause forever can't successful start service expect to restart AccessibilityManagerService

how to know AsyncTask working in background or not?

I am calling one webservice in home page in that i will send all the details in that this process is working in bacground. when i come to this home page again i want to know prvious AsyncTask is end or not
what iam doing exactly here
public void callAsynchronousTask() {
//http://stackoverflow.com/questions/6531950/how-to-execute-async-task-repeatedly-after-fixed-time-intervals
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (vist != null && saves != null && prof != null && semail != null) {
if (vist.getStatus() != AsyncTask.Status.RUNNING) {
if (saves.getStatus() == AsyncTask.Status.PENDING || saves.getStatus() == AsyncTask.Status.FINISHED && saves.getStatus() != AsyncTask.Status.RUNNING)
{
if (prof.getStatus() == AsyncTask.Status.PENDING || prof.getStatus() == AsyncTask.Status.FINISHED && prof.getStatus() != AsyncTask.Status.RUNNING)
{
if (semail.getStatus() == AsyncTask.Status.PENDING || semail.getStatus() == AsyncTask.Status.FINISHED && semail.getStatus() != AsyncTask.Status.RUNNING)
{
checkandsave();
}
}
}
}
} else {
checkandsave();
}
public void checkandsave(){
ConnectionDetector cd = new ConnectionDetector(Home_page.this);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DatabaseToadd da = new DatabaseToadd(Home_page.this);
mu = new ArrayList<>();
mu = da.getAllUser();
if (mu.size() > 0) {
vist = new Getvisiterid();
saves=new SaveVisitor();
semail=new sendemail();
prof=new saveprofpic();
vist.executeOnExecutor(THREAD_POOL_EXECUTOR);
}
}
else {
System.out.println("null db");
}
but in this when i come back to this actvity if asynctask running in background then also its showing null if i create object on top its showing pending
Based on your text I'm making the assumption you only need this task run in this activity, and dont need multiple tasks run at once. If this is the case use an asynctaskloader. The asynctask is tied to the lifecycle of the activity and you receive callbacks when it is starting, running in background, and done.
AsyncTaskLoader basic example. (Android)

How to check displaying mock location in android? [without using location]

I need to check whether any fake app using location in developer settings. So that I need to make user to change it to developer setting.
But I need to use without using location. I tried this method but this displays not enabled toast message eventhough I enabled the fake app location.
public static boolean isMockLocationEnabled(Context context)
{
boolean isMockLocation = false;
try {
//if marshmallow
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AppOpsManager opsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
} else {
// in marshmallow this will always return true
isMockLocation = !android.provider.Settings.Secure.getString(context.getContentResolver(), "mock_location").equals("0");
}
} catch (Exception e) {
return isMockLocation;
}
return isMockLocation;
}
MainActivity:
#Override
protected void onStart() {
super.onStart();
if (AppUtils.isMockLocationEnabled(this)) {
Log.e("Location..............", "enabled");
} else {
Log.e("Location..............", "not enabled"); //it always goes here in 8.0
}
}
So without location, how to pass? Because I just need to check whether fake location is using or not?
//location.isFromMockProvider(); // without location how to use?
So any other solution?
You can check whether the Mock options is ON:
if (Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else
return true;
Or you can detect if there is an application which is using Mock:
boolean isExisted = false;
PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo applicationInfo : packages) {
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
if (requestedPermissions[i]
.equals("android.permission.ACCESS_MOCK_LOCATION")
&& !applicationInfo.packageName.equals(context.getPackageName())) {
isExisted = true;
break;
}
}
}
} catch (NameNotFoundException e) {
Log.e("Got exception " , e.getMessage());
}
}

what is the difference between FLASH_MODE_TORCH AND FLASH_MODE_ON

My app turn on camera LED using FLASH_MODE_TORCH, but now some people say that FLASH_MODE_TORCH will not work on some Samsung devices correctly.
So should I use FLASH_MODE_ON for all devices to work?(especially for Samsung devices)
may be this will help you
Parameters params = null;
if(mCamera != null) {
params = mCamera.getParameters();
if(params != null) {
List<String> supportedFlashModes = params.getSupportedFlashModes();
if(supportedFlashModes != null) {
if(supportedFlashModes.contains(Parameters.FLASH_MODE_TORCH)) {
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
} else if(supportedFlashModes.contains(Parameters.FLASH_MODE_ON)) {
params.setFlashMode( Parameters.FLASH_MODE_ON );
} else mCamera = null;
} else Log.d(TAG, "Camera is null.");
if(mCamera != null) {
Log.d(TAG, "Flash disponibile (" + params.getFlashMode() + ")");
mCamera.setParameters( params );
mCamera.startPreview();
mCamera.autoFocus(null);
} else Log.d(TAG, "Camera is null.");
There is no single way to make sure the flash works on every device. You have to add a lot of code that is specific of the manufacturer and the device.
Dwhanik's answer is how I would handle the specific problem you are talking about. Check for FLASH_MODE_TORCH first and then try FLASH_MODE_ON. But this does not mean that you will get a flash on every device.
public void Initialize(){
if (this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
camManager = (CameraManager) getSystemService(this.CAMERA_SERVICE);
try {
if (camManager.getCameraIdList().length > 0) {
strCameraID=camManager.getCameraIdList()[0];
}
} catch (Exception EX_CAMLIST) {
}
}
}
public void switchLED(String strCemeraID,boolean status){
if(camManager==null || strCemeraID==null)return;
try {
if (strCemeraID.length() > 0) {
camManager.setTorchMode(strCemeraID, status);
}
} catch (Exception EX_CAMERA_TORCH) {
}
}

continuous sending of data

The android application is bulit in such a way that when data is being sent(on clicking the button) to the usb device ,LED toggles and the data is being displayed. I want data to be sent continuously without any manual intervention. Kindly help
if (mInputStream != null)
{
int Data = 0;
try {
Data = mInputStream.read();
} catch (IOException e) {
}
if (Data == LED_ON)
{
ledStatus.setText("LED is ON");
}
else if (Data == LED_OFF)
{
ledStatus.setText("LED is OFF");
}
else
{
ledStatus.setText("Request failed");
}
}
else
{
ledStatus.setText("mInputStream == null");
}
this time I have tested it myself...
it should definitely work
paste it in your onCreate() good luck :)
Timer t = new Timer();
t.schedule(new TimerTask(){
public void run(){
// write the method name here. which you want to call continuously
Log.d("timer", "timer");
}
},10, 1000);

Categories

Resources