2017-05-29 129 views
0

我有简单的应用程序来测试android:进程属性的服务。所以,我的服务是这样的:服务与android:进程不启动

public class MyService extends IntentService { 
    static final String TAG = "MyService"; 

    public MyService() { 
     super("MyService"); 
    } 
    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.d(TAG,"onCreate()"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     doJob(); 
     return START_STICKY; 
    } 

    private void doJob() { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       Log.i(TAG,"job started"); 

       try { 
        Thread.sleep(5000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       Log.i(TAG,"job stopped"); 

       stopSelf(); 
      } 
     }).start(); 
    } 
} 

我试图从活动启动服务如下:

findViewById(R.id.startServiceBtn).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       startService(new Intent(getApplicationContext(),MyService.class)); 
      } 
     }); 

一切工作正常。现在我在清单中的服务声明中添加了android:process =“:service”属性。之后,服务不会启动。那么,为什么这样,我应该在独立的过程中更改启动服务?

+0

你是如何检查,如果你的服务运行? – F43nd1r

+0

这不是你的问题,但你使用意图服务错误。你不应该在onStartCommand中为intent服务做任何事情 - 它应该都在onHandleIntent中。通过在onStartCommand中执行它,您将打破IntentService内置的处理请求的方法。 –

+0

@ F43nd1r我使用Studio监视器选项卡在工作室中检查它,服务应该启动doJob()方法,将消息打印到logcat。如果我看到这些消息,那么这意味着服务正在运行 – borune

回答

0

我认为你必须做这个任务,即onHandleIntent()中的dowork()方法调用。因为你的服务类扩展了Intent服务而不是Service。

public class MyService extends IntentService { 
static final String TAG = "MyService"; 

public MyService() { 
    super("MyService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
doJob(); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 


} 

private void doJob() { 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      Log.i(TAG,"job started"); 

      try { 
       Thread.sleep(5000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      Log.i(TAG,"job stopped"); 

      stopSelf(); 
     } 
    }).start(); 
} 

}

+0

你说得对,他错误地实现了它,但这不是他的问题 - 它会按照他写的方式运行,它不会正确处理意图。 –

+0

@Sandeep库马尔从onStartCommand替换doJob到onHandleIntent不帮助 – borune

0

哦对不起,这是愚蠢的错误 - 我必须选择Android的显示器选项卡新工艺)感谢所有