Service stops on clearing data from settings - android

in my app i run a service in which i keep record of incoming and out going calls on text file(saved it on internal storage) using broadcastReciever. but when i press clear data button(settings=>apps=>Myapp=>clear data) my service also stops. i used Log.d() in onDestroy() method but it is not logged in logcat when i press clear data.
i read this question having same problem but i didn't find any solution. then i went through Developer Guide. i am really confused.

The data associated the the app will no longer persist on clearing. To avoid this you need to sign your app as a system app.
Clear Data does kill the app, and always has.
"Force Stop" has gone through various iterations of meanings. It used
to mean to just kill all processes and services, and clearing data
would also do the same as a force stop. There were also older
iterations of the platform that were not as good as figuring out when
to disable the button, which is probably why you are seeing it remain
enabled in 2.2.
However in 3.2 I believe the meaning of "Force Stop" change to put the
application in a state where it would not be able to run until the
user had done something to explicitly start it (such as launching it
from launcher, selecting it as an input method, etc). When that change
was made, "Clear Data" continued to just kill the processes and stop
its services, so the app was not in the full stopped state so the
button remains enabled.
Edit:
Example of working code:
Step 1) Create one Android BroadCastReciever and register it for two action
Manifest
<service android:name="ServiceTest" >
</service>
<receiver android:name="ReceiverCall" >
<intent-filter>
<action android:name="com.android.techtrainner" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
com.android.techtrainner is the custom action. BroadCastReceiver Class contain code to restart service again
public class ReceiverCall extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Service Stops", "Ohhhhhhh");
context.startService(new Intent(context, ServiceTest.class));;
}
}
Step 2) Create Android service class , do some task there (I have taken one Timer to print Log) and in onDestory()
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.android.techtrainner");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
}

Related

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

Android Application onCreate not called for homescreen launcher app during reboot

I am having a strange problem in an Android application that I am building, the application is basically a Homescreen replacement app which will be put as a default homescreen in a device. To do some initialization work I have extended Android Application class and in the onCreate() method I am basically registering some observer and starting a service, here's the code:
public class MyApplication extends Application implements ExternalStorageListener {
private ExternalStorageObserver externalStorageObserver;
public void onCreate() {
Log.i("MyApplication", "Starting application");
super.onCreate();
externalStorageObserver = new ExternalStorageObserver(this);
if(externalStorageObserver.isExternalStorageAvailable()) {
// this builds a list of files present in the SD card
// which is being used through the application to do
// some work
buildData();
File externalFileDir = getApplicationContext().getExternalFilesDir(null);
if(externalFileDir != null && externalFileDir.isDirectory()) {
// do something...
}
}
//Register listener to observe external storage state
registerExternalStorageObserver();
Log.i("SyncService", "Starting sync service...");
ComponentName cmp = startService(new Intent(getApplicationContext(), SyncService.class));
Log.i("SyncService", cmp.toString());
}
private void registerExternalStorageObserver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
registerReceiver(externalStorageObserver, filter);
}
private void buildData() {
// builds a list
}
}
Content of Manifest file:
<application android:persistent="true" android:icon="#drawable/icon"
android:label="#string/app_name" android:name="com.webgyani.android.MyApplication"
android:debuggable="true">
<activity android:name=".HomeTabActivity" android:launchMode="singleInstance"
android:stateNotNeeded="true" android:theme="#style/LightTabsTheme"
android:screenOrientation="landscape" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
This works fine when I install the app either using Eclipse or manually installing the apk onto the device. Once the app is installed things work fine, I mean the above onCreate() method gets called and service is also started normally, but if I reboot the device this time the onCreate() method does not get called(none of the log statements appear and also the services are not started). After some debugging I noticed that this only happens if I set my app as the default launcher/homescreen app and thereafter reboots the device, because once you set the app as the default launcher, Android should automatically launch your app as the homescreen after reboot. In my case the app is launched but that code is not executed.
I tried to use debugger but that didn't work because when I reboot the device the debugger gets disconnected and by the time USB debugging gets enabled my app is already started.
I even double checked the Logcat but didn't see any error. I thought of having a BOOT_COMPLETED intent to initialize that part, but that will require some code refactoring which I am not willing to do at this point of time unless there is a solution.
So I am curious to know that whether this is a standard behavior, or is there a known bug which causes this, because my assumption is the onCreate method of the Application will always get called whenever the app is started. I have tried whatever I could since morning, but nothing worked, couldn't pinpoint the issue, if any of you could shed some light into this then that would be highly appreciated.
Thanks
Well, finally I figured out the problem, and it was in my code itself. I initially suspected that the MyApplication's onCreate() method was not getting called, I had that assumption because I was not able to see any logs. To know whether the method is getting called or not, instead of using Log.i() I was also appending some additional log messages in an ArrayList and printing them later, this revealed that the methods were indeed getting called and even the Service was instantiating properly but the data or filelist is not being populated because the SDCard was not ready by that time. I am also pretty sure that the logs were not available on Logcat due to the fact that the USB debugger becomes ready after my app is started(as it's a homescreen app).
The actual problem becomes obvious when you see that my overridden MyApplication class implements a listener called ExternalStorageListener which basically extends BroadcastReceiver, I have created that class to receive SDCard related Intents for example ACTION_MEDIA_MOUNTED, ACTION_MEDIA_REMOVED to rebuild the data(file list). In my case the ExternalStorageListener class was not receiving the Intents because I forgot to add this filter.addDataScheme("file") in the registerExternalStorageObserver method above in the code sample.
I do agree that my question was based on a false assumption and the code example I posted it's kind of hard to figure out the actual issue. I am not sure what to do with the question whether to mark this as answer or leave it as it is.

What is the cleanest way to create a GUIless application?

Good Morning.
I have a question about how to create an application without GUI. It should start when the user pushes the icon. Reading other posts, seems that the natural way of doing this would be a Service.
Since the app has no GUI, it makes no sense to add any Activity. For this reason, the Service has to be unbinded. So, if there is no component calling startService, and no external component is sending an intent, ¿how does the service start?
Is there any attribute in the manifest to achieve this? Or maybe extending Application and using onCreate to start the service?
Thanks.
UPDATES:
-There's no way to start a Service in the same app without an Intent. Other options would be autostart or Broadcast receivers, but these don't fit my requirements.
-Tried a test app without Activities, and the icon isn't even showing in the launcher. Don't know the reason of this, maybe related to the manifest not having a LAUNCHER activity.
The list of applications shown in the Android launcher is basically the list of all activities in the system that have a LAUNCHER intent filter:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
If you put this intent filter on a <service>, it will not work (just tried). Thus, the only way to do what you want to do is through an Activity. I think the cleanest way is something like this:
public void onCreate(Bundle savedInstanceState) {
Intent service = new Intent(this, MyService.class);
startService(service);
Toast.makeText(this, "Service started.", Toast.LENGTH_SHORT).show();
finish();
}
The user will not see anything except a small message at the bottom of the screen saying "Service started." that will automatically disappear in a couple of seconds. It's clean and user-friendly.
The service is started either when somebody calls startService() or when somebody calls bindService(). Note that if service is only started via bindService() it will be automatically stopped when Activity either explicitly unbinds from it or is destroyed (and it was the only binder).
You can declare BOOT_COMPLETED_ACTION broadcast receiver in your AndroidManifest.xml and start your service on system boot. But you service will only start on next device reboot. And there are some issues with applications without activities and this broadcast event in Android 3.1. More info can be found here.
In general, its good to have at least one activity in your application, even if your primary component is service. This activity will start the service when user launches it, and also may expose some ability to configure the service behavior.
Example of activity that starts service:
public class ServiceStarterActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
startService(new Intent(this, ServiceA.class));
finish();
}
}

Categories

Resources