无法 运行 服务中的任务

Cannot Run Tasks in Service

我知道这是一个基本问题,我是 android 服务的新手。我研究了 Google 和 Whosebug。 Whosebug 中有很多问题与我的主题相关或相似,但我无法得到正确的答案,我被转移到不同的主题。

这是我运行宁的简单测试代码

public class Service extends android.app.Service {

private Handler mHandler;

private void ping() {
    try {
        Log.e("Tag", "Success");
        Toast.makeText(getApplicationContext(), "Service Ping", Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        Log.e("Error", "In onStartCommand");
        e.printStackTrace();
    }
    scheduleNext();
}

private void scheduleNext() {
    mHandler.postDelayed(new Runnable() {
        public void run() { ping(); }
    }, 3000);
}

public int onStartCommand(Intent intent, int x, int y) {
    mHandler = new android.os.Handler();
    ping();
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

在此过程中,每 3 秒弹出一个 Toast 消息并打印一个 Log 消息,即使在应用程序最小化时也能正常工作。但是当我完全退出应用程序时,没有打印 Toast 或 Log。在这个 SO ANSWER 中清楚地说明了为什么没有 UI 就不能调用 Toast 消息。而且我无法打印日志,因为进程正在被终止。

基本上,我希望服务每 5 分钟在后台 运行 运行一次,并且需要从网上获取数据。我应该如何实施该服务?是否有任何示例代码或教程值得赞赏?

当您启动一个服务时,默认情况下它与启动它的任何组件运行在相同的进程中。当该组件处于 运行 的进程退出时,服务也会退出。为了在自己的进程中启动服务,您需要在清单中执行以下操作:

    <service
        android:name=".Service"
        android:enabled="true"
        android:exported="false"
        android:process=":separate_service_process"
        android:stopWithTask="false" >
    </service>

android:process属性的标签前加一个冒号告诉系统在单独的进程中启动服务,android:stopWithTask属性告诉系统保持服务存活即使启动它的组件停止了。有关清单设置的更多信息,请参阅 http://developer.android.com/guide/topics/manifest/service-element.htmlstopWithTask 属性是 ServiceInfo class 的一部分)。

现在使用 startService(Intent) 启动您的服务,您应该已准备就绪。祝你好运!

PS--我建议将您的服务 class 重命名为独特的名称,以避免与基本服务 class.

混淆