Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?

前端 未结 8 571
陌清茗
陌清茗 2020-11-30 02:24

I am trying to run a service in the background. What my app does is when user checks checkbox then service starts and when it is unchecked service is stopped. Which is worki

相关标签:
8条回答
  • 2020-11-30 02:53

    You can try to restart service on onDestroy event of service. Use some flags to find if service is closed by the User or its force closed.

    Note that there is not guarantee that onDestroy will be called everytime.

    0 讨论(0)
  • 2020-11-30 02:55

    use my method if you want to start a hidden app for just first time I make a transparent Launcher activity like this

    <activity android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/Theme.Transparent"
        android:excludeFromRecents="true"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    

    So I make the app hidden in launcher by placing this code in oncreat() [Code]

    PackageManager p = getPackageManager();
        ComponentName componentName = new ComponentName(this, MainActivity.class); // activity which is first time open in manifiest file which is declare as <category android:name="android.intent.category.LAUNCHER" />
    p.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
    

    So I use this code for show app icon on launcher and make it run able on service class that use broadcast receiver boot and in network connection broadcast receiver class too(autostart.java and networkConnectinCheck.java):

    PackageManager p = context.getPackageManager();
        ComponentName componentName = new ComponentName(context, MainActivity.class);
        p.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    

    Now I can run app for first time by user hands and after this I use my receiver's to lunch app any time.

    0 讨论(0)
提交回复
热议问题