Why does TileService wait several seconds to start an Activity? - android

I'm using a TileService as a shortcut to open my app's Activity. It does only that, and has no state.
It looks like this:
class QuickAccessTileService : TileService() {
override fun onClick() {
super.onClick()
val intent = Intent(this, SlideOverActivity::class.java)
.addFlags(FLAG_ACTIVITY_NEW_TASK)
startActivityAndCollapse(intent)
}
}
and it's declared in AndroidManifest as:
<service
android:name=".service.QuickAccessTileService"
android:icon="#drawable/ic_home"
android:label="#string/tile_label"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
</service>
As it stands, this works. However, when my application is stopped, the next time I try to open it via the quick settings panel, it takes several seconds to start the activity.
Here's what I know:
The Activity in itself isn't slow to start. Trying to open it via the launcher instead makes it quite clear.
The Service seems to be what's taking a while to start before onClick is even executed. It makes sense; the Service is probably not kept running in the background doing nothing while the app isn't running. However, this means that when the system detects a click on my Tile, the Service has to be recreated first, which takes way too long.
I'm not sure where to go from here — if my guesses are even right.
EDIT: As an important addition, I can reproduce this on a OnePlus 7 Pro running on Android Pie. This might be a OnePlus-specific issue as I cannot reproduce it on an emulator.

#RequiresApi(Build.VERSION_CODES.N)
class TileSettingClass : TileService() {
override fun onClick() {
super.onClick()
val tile = qsTile
if (tile.state == Tile.STATE_INACTIVE) {
tile.state = Tile.STATE_ACTIVE
val intent = Intent(this.applicationContext, YourActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.action = "yourAction"
applicationContext.startActivity(intent)
} else {
tile.state = Tile.STATE_INACTIVE
}
tile.updateTile()
}
}
Manifests
<service
android:name=".main.service.TileSettingClass"
android:icon="#drawable/ic_tile_setting"
android:label="#string/milliy"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
>
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
</service>

Related

Android - My app replaces the app which shared its content

I'm developing an app that receives data using intents(ACTION_SEND). I've discovered a weird issue when I'm sharing content from Chrome(only happens in Chrome 83 or above, older versions can't reproduce the issue) for instance, if the content is only selected text, for example, the data reaches my app correctly, but if the content shared is a URL, it reaches my app, but suddenly my app replaces Chrome in the app switcher. So, if I have my app and Chrome opened, after the data sharing I have two instances of my app(even if the Chrome icon appears in top of that window, if I tap it, opens my app).
Any ideas about what is going on here? It's worth to notice that I can't reproduce this using Firefox.
My activity code:
class MainActivity : HybridActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("MyApp", "onCreate")
super.onCreate(savedInstanceState)
val testButton = Button(this)
setContentView(testButton)
}
override fun onStart(){
super.onStart()
var bundle = intent.getExtras();
Log.d("MyApp", "onStart intent tostr: " + intent.toString())
if (bundle != null) {
bundle.keySet().forEach {
Log.d("MyApp", "EXTRA:" + it + "=" + bundle.get(it));
}
}
}
override fun onResume() {
super.onResume()
Log.d("MyApp", "onResume")
}
}
Intent filter is defined in the manifests like this:
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
<data android:mimeType="image/*" />
<data android:mimeType="video/*" />
</intent-filter>
PS: Don't know if this is related but I've changed the launch mode in the manifest to singleInstance and the issue still is reproducible...
PS2: I have added this activity dump, produced just as the issue appeared:
https://gist.github.com/Leprosy/f63bf02bb1c2887f0e419799d98635ab
Your app is actually not replacing chrome, but instead the share link intent receiver activity from your app arrives at the top of the chrome task. It's still the chrome task, it's just that the top activty is from your app. This ensures that pressing back results in going back to chrome, even if you would switch apps a few times first.
As a workaround, you could detect this, and in that case, create a new intent to launch a new activity and close the one that directly received it.
Edit: I tested this and it can be done in the following way:
import android.app.Activity
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.os.Bundle
class ExternalTextReceiverActivity : Activity() {
val CUSTOM_EXTRA_NAME = "RELAUNCHED"
override fun onCreate(savedInstanceState: Bundle?) {
if (!intent.getBooleanExtra(CUSTOM_EXTRA_NAME, false)) {
this.finish()
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(CUSTOM_EXTRA_NAME, true);
startActivity(intent);
}
super.onCreate(savedInstanceState);
// The rest of your onCreate code here
}
}
If you only want this for chrome specifically, then you can use this code:
import android.app.Activity
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.os.Bundle
class ExternalTextReceiverActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
if (intent.getIntExtra("org.chromium.chrome.extra.TASK_ID", -1) == this.taskId) {
this.finish()
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
super.onCreate(savedInstanceState);
// The rest of your onCreate code here
}
}
Combine in both cases with android:launchMode="singleInstance" or android:launchMode="singleTask" for your Activity in the Android Manifest to make sure it does not open multiple tasks for this same activity.
Update 2
So I have done some more research and it seems that this only happens when using the android sharesheet. When the app that shares the data uses the intent resolver the activity is opened in a new task/instance. For example the sharing function in firefox does handle it correctly. Unfortunately I could not find anything related to this and how you could fix it.
Original Answer
I think that this a wanted behavior as your app is handling the url and it is not opened in your app.
Update
This is what the offical docs say about implicit deep links you are using:
An implicit deep link is a URI that refers to a specific destination in an app. When a URI is invoked—for example, when a user clicks a link—Android can then open your app to the corresponding destination.
When triggering an implicit deep link, the state of the back stack depends on whether the implicit Intent was launched with the Intent.FLAG_ACTIVITY_NEW_TASK flag:
If the flag is set, the task back stack is cleared and replaced with the deep link destination. As with explicit deep linking, when nesting graphs, the start destination from each level of nesting—that is, the start destination from each element in the hierarchy—is also added to the stack. This means that when a user presses the Back button from a deep link destination, they navigate back up the navigation stack just as though they entered your app from its entry point.
If the flag is not set, you remain on the task stack of the previous app where the implicit deep link was triggered. In this case, the Back button takes you back to the previous app, while the Up button starts your app's task on the hierarchical parent destination within your navigation graph.
From my understanding that means, that only the app that launches your app can change this behavior.
Source: https://developer.android.com/guide/navigation/navigation-deep-link#implicit

navigate back after handling intent-filter

I have an application. I want it to appear when I tap "share" in other applications. Then I want it to process the data it has received and go back to the caller application.
E.g. I am sharing a facebook post:
1) My app opens
2) Saves info to DB
3) Returns to FB post
How can this return to FB post be achieved?
I tried referring to callingActivity, but it is null.
Intent filter:
<intent-filter android:label="#string/app_name">
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*/*"/>
</intent-filter>
Activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = intent
val action = intent.action
val type = intent.type
if (intent.getStringExtra(Intent.EXTRA_TEXT) != null) {
// do some processing
// goes recursively
startActivity(intent)
}
}
Whatever app you shared from will be active behind your current application so you will be able to share to your app and then just stop your app using finish(). I did a quick test and was able to share from a couple of apps using this approach. Your app will flash up then the user will land back in the app they shared from after your database write is complete. I logged the intent to make sure it was coming through properly and was able to see links from chrome (as an example).
if (intent.getStringExtra(Intent.EXTRA_TEXT) != null) {
// do some processing
Log.d("Extras", intent.getStringExtra(Intent.EXTRA_TEXT))
// goes recursively
finish()
}

How to lock uninstalling an application with a password? [duplicate]

First of all, I have researched a lot about my issue, but I could not find a proper solution so I am posting my query here. Hope to get a better solution to the issue:
I have a requirement where I need to ask for password to the user before user deletes my app from settings or from any other application like MyAppSharer. I have found one solution where I can successfully be able to call my activity when user clicks on Uninstall button. I have applied trick here, and calling service. In service, I run timer which runs every 1 second and in that one second, it checks for top most activity of running task. This is running perfectly as per expected.
Now, my issue is, this activity apppears on each of application user tries to uninstall. I need that the activity which I call, should only appear for my application when user tries to uninstall my application.
Here is my code:
public static final String PACKAGE_INSTALLER = "com.android.packageinstaller";
public static final String PACKAGE_INSTALLER_UNINSTALL_ACTIVITY = "com.android.packageinstaller.UninstallerActivity";
alarmTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);;
ComponentName topActivity = mActivityManager.getRunningTasks(1).get(0).topActivity;
final String packageName = topActivity.getPackageName();
String className = topActivity.getClassName();
Log.v(TAG, "packageName:" + packageName);
Log.v(TAG, "className:" + className);
if (PACKAGE_INSTALLER.equals(packageName)
&& PACKAGE_INSTALLER_UNINSTALL_ACTIVITY.equals(className)) {
//Here I need to apply one condition where package name received to be matched with my package name. But I am not sure how to fetch package name of selected application for uninstalling
//To Cancel Existing UninstallerActivity and redirect user to home.
Intent homeIntent = new Intent();
homeIntent.setAction(Intent.ACTION_MAIN);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
homeIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(homeIntent);
//To open my activity
Intent loginActivity = new Intent(UninstallService.this, Act_Login.class);
loginActivity.putExtra(Constants.KEY_IS_FROM_SERVICE, true);
loginActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loginActivity);
}
}
}, 0, 1000);
you should try something like the following :
1st - declare your broadcast recevier in the Manifest file , that will listen to QUERY_PACKAGE_RESTART :
<receiver android:name=".UninstallReceiver">
<intent-filter android:priority="999999">
<action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
<data android:scheme="package" />
</intent-filter>
</receiver>
2nd - your UnunstallIntentReceiver java class like the following :
public class UninstallReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// fetching package names from extras
String[] packageNames = intent.getStringArrayExtra("android.intent.extra.PACKAGES");
if(packageNames!=null){
for(String packageName: packageNames){
if(packageName!=null && packageName.equals("application_package")){
// start your activity here and ask the user for the password
}
}
}
}
}
and please give me some feedback
Hope That Helps.
If this is a corporate requirement (if you want to block a regular user from uninstalling your app, no chance, thanks Google for protecting us from bad devs), you should create a device administrator application. This way, although the user still can delete the app, it's one extra step if you want to prevent accidental erasing.
Before deleting your app, if it's enabled as device admin, the user must first disable the app as administrator, and the app receives this broadcast.
In your XML, put
<activity android:name=".app.DeviceAdminSample"
android:label="#string/activity_sample_device_admin">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<receiver android:name=".app.DeviceAdminSample$DeviceAdminSampleReceiver"
android:label="#string/sample_device_admin"
android:description="#string/sample_device_admin_description"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/device_admin_sample" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
In the receiver, you have at least two methods worth noticing:
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
…
}
#Override
public void onDisabled(Context context, Intent intent) {
…
}
This way you know the user is potentially going to erase your app.
Complete guide for device administration is at https://developer.android.com/guide/topics/admin/device-admin.html
If you have root permissions make your app system (remove your apk-file from /data to /system directories). Then reboot device. After reboot your app is not available to delete by user (not superuser).
The only way i see, is to provide your own uninstaller as part of your app (= an activity that lists all apps and allows to uninstall them). Your service could then check if your app was the one that started the packageinstaller and if not redirect the user.
It is not possible (at least on the Android 4.4 I tested with) to grab the uninstaller activity data without root or being a system app. This is because the uninstaller is not called as an independent task, but as an activity on the stack of the starting task (which is the Settings app when uninstalling from settings, etc). You can only see the Task details of the calling task.
However there might be some really dirty possibility left, that i didn't test to the end: You could register the hidden interface IThumbnailReceiver [1] with the hidden three argument version of ActivityManager.getRunningTasks [2]. It seems like only the GET_TASKS permission is needed to grab a thumbnail (see [3]). It should be possible to find out which app is going to be removed from the app thumbnail... - But as this solution uses hidden APIs, there is no guarantee that it will work with older/newer/vendored Android versions.
https://github.com/omnirom/android_frameworks_base/blob/android-4.4/core/java/android/app/IThumbnailReceiver.aidl
https://github.com/omnirom/android_frameworks_base/blob/android-4.4/core/java/android/app/ActivityManager.java#L766
https://github.com/omnirom/android_frameworks_base/blob/android-4.4/services/java/com/android/server/am/ActivityManagerService.java#L6725

Ask for password before uninstalling application

First of all, I have researched a lot about my issue, but I could not find a proper solution so I am posting my query here. Hope to get a better solution to the issue:
I have a requirement where I need to ask for password to the user before user deletes my app from settings or from any other application like MyAppSharer. I have found one solution where I can successfully be able to call my activity when user clicks on Uninstall button. I have applied trick here, and calling service. In service, I run timer which runs every 1 second and in that one second, it checks for top most activity of running task. This is running perfectly as per expected.
Now, my issue is, this activity apppears on each of application user tries to uninstall. I need that the activity which I call, should only appear for my application when user tries to uninstall my application.
Here is my code:
public static final String PACKAGE_INSTALLER = "com.android.packageinstaller";
public static final String PACKAGE_INSTALLER_UNINSTALL_ACTIVITY = "com.android.packageinstaller.UninstallerActivity";
alarmTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);;
ComponentName topActivity = mActivityManager.getRunningTasks(1).get(0).topActivity;
final String packageName = topActivity.getPackageName();
String className = topActivity.getClassName();
Log.v(TAG, "packageName:" + packageName);
Log.v(TAG, "className:" + className);
if (PACKAGE_INSTALLER.equals(packageName)
&& PACKAGE_INSTALLER_UNINSTALL_ACTIVITY.equals(className)) {
//Here I need to apply one condition where package name received to be matched with my package name. But I am not sure how to fetch package name of selected application for uninstalling
//To Cancel Existing UninstallerActivity and redirect user to home.
Intent homeIntent = new Intent();
homeIntent.setAction(Intent.ACTION_MAIN);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
homeIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(homeIntent);
//To open my activity
Intent loginActivity = new Intent(UninstallService.this, Act_Login.class);
loginActivity.putExtra(Constants.KEY_IS_FROM_SERVICE, true);
loginActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loginActivity);
}
}
}, 0, 1000);
you should try something like the following :
1st - declare your broadcast recevier in the Manifest file , that will listen to QUERY_PACKAGE_RESTART :
<receiver android:name=".UninstallReceiver">
<intent-filter android:priority="999999">
<action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
<data android:scheme="package" />
</intent-filter>
</receiver>
2nd - your UnunstallIntentReceiver java class like the following :
public class UninstallReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// fetching package names from extras
String[] packageNames = intent.getStringArrayExtra("android.intent.extra.PACKAGES");
if(packageNames!=null){
for(String packageName: packageNames){
if(packageName!=null && packageName.equals("application_package")){
// start your activity here and ask the user for the password
}
}
}
}
}
and please give me some feedback
Hope That Helps.
If this is a corporate requirement (if you want to block a regular user from uninstalling your app, no chance, thanks Google for protecting us from bad devs), you should create a device administrator application. This way, although the user still can delete the app, it's one extra step if you want to prevent accidental erasing.
Before deleting your app, if it's enabled as device admin, the user must first disable the app as administrator, and the app receives this broadcast.
In your XML, put
<activity android:name=".app.DeviceAdminSample"
android:label="#string/activity_sample_device_admin">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<receiver android:name=".app.DeviceAdminSample$DeviceAdminSampleReceiver"
android:label="#string/sample_device_admin"
android:description="#string/sample_device_admin_description"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/device_admin_sample" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
In the receiver, you have at least two methods worth noticing:
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
…
}
#Override
public void onDisabled(Context context, Intent intent) {
…
}
This way you know the user is potentially going to erase your app.
Complete guide for device administration is at https://developer.android.com/guide/topics/admin/device-admin.html
If you have root permissions make your app system (remove your apk-file from /data to /system directories). Then reboot device. After reboot your app is not available to delete by user (not superuser).
The only way i see, is to provide your own uninstaller as part of your app (= an activity that lists all apps and allows to uninstall them). Your service could then check if your app was the one that started the packageinstaller and if not redirect the user.
It is not possible (at least on the Android 4.4 I tested with) to grab the uninstaller activity data without root or being a system app. This is because the uninstaller is not called as an independent task, but as an activity on the stack of the starting task (which is the Settings app when uninstalling from settings, etc). You can only see the Task details of the calling task.
However there might be some really dirty possibility left, that i didn't test to the end: You could register the hidden interface IThumbnailReceiver [1] with the hidden three argument version of ActivityManager.getRunningTasks [2]. It seems like only the GET_TASKS permission is needed to grab a thumbnail (see [3]). It should be possible to find out which app is going to be removed from the app thumbnail... - But as this solution uses hidden APIs, there is no guarantee that it will work with older/newer/vendored Android versions.
https://github.com/omnirom/android_frameworks_base/blob/android-4.4/core/java/android/app/IThumbnailReceiver.aidl
https://github.com/omnirom/android_frameworks_base/blob/android-4.4/core/java/android/app/ActivityManager.java#L766
https://github.com/omnirom/android_frameworks_base/blob/android-4.4/services/java/com/android/server/am/ActivityManagerService.java#L6725

Need to switch my app to background after a phone restart or power on

I need my android app to be in background mode after a phone restart/power on.
Currently I am using the following code, so that my app successfully gets launched after a phone restart/power on.
AndroidManifest.xml:
<receiver android:enabled="true" android:name="my_package.BootUpReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
BootUpReceiver.java:
public class BootUpReceiver extends BroadcastReceiver
{
private static SharedPreferences aSharedSettings;
#Override
public void onReceive(Context context, Intent intent)
{
aSharedSettings = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
boolean isUserLoggedIn = aSharedSettings.getBoolean(Key.AUTHENTICATED, false);
if(isUserLoggedIn)
{
Intent aServiceIntent = new Intent(context, MyHomeView.class);
aServiceIntent.addCategory(Intent.CATEGORY_HOME);
aServiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(aServiceIntent);
}
}
}
As I said above, my app successfully gets launched after a phone restart/power on.
However, after the phone restart/power on, my app was in foreground mode. But I need my app to be in background mode.
Can anyone please say, how to make an app to be in background mode after a phone restart or power on.
I even tried by changing the intent category to
<category android:name="android.intent.category.HOME" />
But no use in it. Can anyone please help me?
Thanks.
I need my app to be just running in background after the phone restart, so that users can select from the minimized app
I think your approach is wrong. All you are trying to do now is to add icon of your app to recent apps list. Your app won't run in background and I think you don't really want it. Am I right?
Recent apps list managed by android and IMHO forcing your app to be in recent apps list is not a very good idea. User will start you app when he wants from launcher or icon on his desktop.
If your broadcast receiver is working fine and app is starting successfully then you can use the below code in your MyHomeView activity's onCreate method to go to the home screen.
Trick is to click HOME button programmatically when app starts.
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
you can pass some variable from the BroadcastReceiver to differentiate a normal request and BroadcastReceiver's request to make the above code conditional.
But if you want to execute it always in background then it would be better to use Service.
It is recommended to change your code to the service to run it in background.
The suggestion which Leonidos replied is correct.
However, Just a workaround for this:
In my BootUpReceiver, I had a seperate boolean flag for this! (Its a bad way. but just a workaround)
SharedPreferences.Editor aPrefEditor = aSharedSettings.edit();
aPrefEditor.putBoolean(Key.IS_DEVICE_RESTARTED, true);
aPrefEditor.commit();
In Oncreate method of MyHomeView:
boolean isDeviceRestarted = aSharedSettings.getBoolean(Key.IS_DEVICE_RESTARTED, false);
if(isDeviceRestarted)
{
SharedPreferences.Editor aPrefEditor = aSharedSettings.edit();
aPrefEditor.putBoolean(MamaBearKey.IS_DEVICE_RESTARTED, false);
aPrefEditor.commit();
moveTaskToBack(true);
}
Thanks

Categories

Resources