【问题标题】:Service stops on clearing data from settings服务在从设置中清除数据时停止
【发布时间】:2014-07-25 12:27:06
【问题描述】:

在我的应用程序中,我运行一个服务,在该服务中,我使用broadcastReciever 记录文本文件(保存在内部存储中)的来电和去电。但是当我按下清除数据按钮(设置=>应用程序=>我的应用程序=>清除数据)时,我的服务也停止了。我在onDestroy() 方法中使用了Log.d(),但是当我按下clear data 时它没有登录logcat。 我读了this question 有同样的问题,但我没有找到任何解决方案。然后我通过Developer Guide。我真的很困惑。

【问题讨论】:

  • 请参阅this,这将帮助您引导广播接收器服务于android
  • 关注Link这是适合您的答案。

标签: android android-intent service broadcastreceiver


【解决方案1】:

与应用关联的数据在清除时将不再保留。为避免这种情况,您需要将您的应用程序作为系统应用程序进行签名。

清除数据确实会杀死应用程序,并且总是如此。

“强制停止”经历了多次迭代。它使用了 意味着只是杀死所有进程和服务,并清除数据 也将与强制停止相同。也有较老的 平台的迭代不如弄清楚何时 禁用该按钮,这可能就是您看到它仍然存在的原因 在 2.2 中启用。

但是在 3.2 中,我相信“强制停止”的含义更改为 应用程序处于无法运行的状态,直到 用户已经做了一些事情来明确启动它(例如启动它 从启动器,选择它作为输入法等)。当那个改变 制作完成后,“清除数据”继续只是杀死进程并停止 它的服务,因此该应用程序未处于完全停止状态,因此 按钮保持启用状态。

编辑: 工作代码示例:

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);
}

【讨论】:

  • 我知道相关数据不再存在,但为什么服务停止?我的数据(文件和数据库)与我的服务无关。
  • 那我该如何重启呢??
  • 你需要重新启动你的应用程序,从那里你可以启动你的服务
  • 因为这个应用程序是为员工监控应用程序,用户将无法启动它。那么有什么方法可以让我以编程方式启动服务
  • 在启动时使用 Sticky 标志启动服务是执行此操作的正常方式。
猜你喜欢
  • 2012-04-03
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多