2016-08-31 17 views
0

我想在我的android項目中創建一個服務,但該服務似乎並沒有開始。Android的java服務不工作

package serviceexample.javatechig.com.serviceexample; 

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.util.Log; 

public class HelloService extends Service { 

    @Override 
    public void onCreate() { 
    } 

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


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

    @Override 
    public void onDestroy() { 
    } 
} 

的manifest.xml:

<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/> 

和主要活動:

package serviceexample.javatechig.com.serviceexample; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 

public class MyActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_my); 

     findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(MyActivity.this, HelloService.class); 
       startService(intent); 
      } 
     }); 

     findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(MyActivity.this, HelloService.class); 
       stopService(intent); 
      } 
     }); 
    } 
} 

沒有錯誤,但是當我按下按鈕,該服務不會得到started.onCreate和onStartCommand事件不提高。

+3

可能重複[爲什麼這個簡單服務不啓動?] (http://stackoverflow.com/questions/4759676/why-is-this-simple-service-not-starting) – 0X0nosugar

+0

看看第二個答案:「非常重要:正確地寫下名字空間......」 – 0X0nosugar

+0

我的'在java.do中新建一個你知道什麼是正確的名字? –

回答

0

您在AndroidManifest.xml

使用了錯誤的包名稱替換:

serviceexample.javatechig.HelloService 

serviceexample.javatechig.com.serviceexample.HelloService 

基本上路徑名應該是相同的服務活動和所有

+0

讓我試試吧.. –

+0

無法正常工作。而不是與「.HelloService」一起工作。我認爲這不是清單文件right中的manifest.xml –

+0

,serviceexample.javatechig.HelloService? –

0

您的Service包裝在:

package serviceexample.javatechig.com.serviceexample; 

您在清單使用類名:

<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/> 

這些應該是相同的,以便Service工作。

+0

我試了這個「serviceexample.javatechig.com.serviceexample.HelloService」。不工作 –

0

我最終發現了這個問題。 manifest.xml中的服務標記不是應用程序標記的子標記。如果我顯示整個manifest.xml,您會在一分鐘內找到問題:)