2011-01-22 133 views
93

我想在某個活動啓動時調用服務。所以,這裏的服務類:在Android中啓動服務

public class UpdaterServiceManager extends Service { 

    private final int UPDATE_INTERVAL = 60 * 1000; 
    private Timer timer = new Timer(); 
    private static final int NOTIFICATION_EX = 1; 
    private NotificationManager notificationManager; 

    public UpdaterServiceManager() {} 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     // Code to execute when the service is first created 
    } 

    @Override 
    public void onDestroy() { 
     if (timer != null) { 
      timer.cancel(); 
     } 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startid) { 
     notificationManager = (NotificationManager) 
       getSystemService(Context.NOTIFICATION_SERVICE); 
     int icon = android.R.drawable.stat_notify_sync; 
     CharSequence tickerText = "Hello"; 
     long when = System.currentTimeMillis(); 
     Notification notification = new Notification(icon, tickerText, when); 
     Context context = getApplicationContext(); 
     CharSequence contentTitle = "My notification"; 
     CharSequence contentText = "Hello World!"; 
     Intent notificationIntent = new Intent(this, Main.class); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
       notificationIntent, 0); 
     notification.setLatestEventInfo(context, contentTitle, contentText, 
       contentIntent); 
     notificationManager.notify(NOTIFICATION_EX, notification); 
     Toast.makeText(this, "Started!", Toast.LENGTH_LONG); 
     timer.scheduleAtFixedRate(new TimerTask() { 

      @Override 
      public void run() { 
       // Check if there are updates here and notify if true 
      } 
     }, 0, UPDATE_INTERVAL); 
     return START_STICKY; 
    } 

    private void stopService() { 
     if (timer != null) timer.cancel(); 
    } 
} 

這裏是我怎麼稱呼它:

Intent serviceIntent = new Intent(); 
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager"); 
startService(serviceIntent); 

的問題是,什麼也沒有發生。上述代碼塊在活動的onCreate結束時被調用。我已經調試過,沒有拋出異常。

有什麼想法?

+1

慎用定時器 - AFAIK當你的服務被關閉以釋放在服務重新啓動時,該計時器不會重新啓動。你是對的```START_STICKY```會重啓服務,但是隻有onCreate被調用,並且timer var不會被重新初始化。您可以使用START_REDELIVER_INTENT,報警服務或API 21 Job Scheduler來解決這個問題。 – georg 2015-01-12 22:24:05

+0

如果您忘記了,請確保您已在應用程序標記內使用``在Android清單中註冊服務。 – 2016-09-09 13:22:45

回答

227

也許你沒有清單中的服務,或者它沒有匹配你的動作的<intent-filter>。檢查LogCat(通過adb logcat,DDMS或Eclipse中的DDMS視角)應該會提出一些警告,這可能會有所幫助。

更有可能的是,你應該通過啓動服務:

startService(new Intent(this, UpdaterServiceManager.class)); 
+0

如何調試?從來沒有調用我的服務,我的調試沒有顯示任何東西 – delive 2015-11-09 23:04:12

+0

在任何地方添加一個Log.e標籤shitton:在你啓動服務之前,服務意圖的結果,在它將要傳輸的服務類中(onCreate,onDestroy,任何和所有方法)。 – Zoe 2017-04-10 18:41:04

69
startService(new Intent(this, MyService.class)); 

只是寫這條線是不夠的我。服務仍然沒有工作。

啓動服務從活動:從片段

startService(new Intent(MyActivity.this, MyService.class)); 

啓動服務一切都只能在清單

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 

    ... 

    <service 
     android:name=".MyService" 
     android:label="My Service" > 
    </service> 
</application> 
42

Java代碼開始服務註冊服務後工作:

getActivity().startService(new Intent(getActivity(), MyService.class)); 

MyService.java

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

public class MyService extends Service { 

    private static String TAG = "MyService"; 
    private Handler handler; 
    private Runnable runnable; 
    private final int runTime = 5000; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.i(TAG, "onCreate"); 

     handler = new Handler(); 
     runnable = new Runnable() { 
      @Override 
      public void run() { 

       handler.postDelayed(runnable, runTime); 
      } 
     }; 
     handler.post(runnable); 
    } 

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

    @Override 
    public void onDestroy() { 
     if (handler != null) { 
      handler.removeCallbacks(runnable); 
     } 
     super.onDestroy(); 
    } 

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

    @SuppressWarnings("deprecation") 
    @Override 
    public void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     Log.i(TAG, "onStart"); 
    } 

} 

定義這個服務到項目的清單文件:

下方添加標籤在清單文件:

<service android:enabled="true" android:name="com.my.packagename.MyService" /> 

完成

2

我喜歡讓更多的動態

Class<?> serviceMonitor = MyService.class; 


private void startMyService() { context.startService(new Intent(context, serviceMonitor)); } 
private void stopMyService() { context.stopService(new Intent(context, serviceMonitor)); } 

不要忘了清單

<service android:enabled="true" android:name=".MyService.class" /> 
-2

Activty:startService(new Intent(this,ChatService.class));

清單 -

<service 
    android:name=.ChatService" 
    android:enabled="true" 
    android:process=":ChatProcess"/>