2011-01-22 20 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

- 私の知る限りをあなたのサービスが無料になるまでシャットダウンするとリソースは、サービスが再開されたときに再起動されません。あなたが正しいです。 '' 'START_STICKY'''はサービスを再起動しますが、onCreateだけが呼び出され、タイマーvarは再初期化されません。これを修正するには、 '' 'START_REDELIVER_INTENT'''、Alarmサービス、またはAPI 21 Job Schedulerで遊ぶことができます。 – georg

+0

忘れた場合は、アプリケーションタグ内の ''を使用して、Androidマニフェストにサービスを登録してください。 –

答えて

227

あなたのマニフェストにサービスがないか、おそらくあなたの行動に一致する<intent-filter>がありません。 LogCatを調べると(adb logcat、DDMS、またはEclipseのDDMSパースペクティブ)、警告が表示されるはずです。

より

おそらく、あなたは介してサービスを開始する必要があります。ただ、この行を書き

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

どのようにデバッグできますか?デバッグに何も表示されない – delive

+0

サービスを開始する前に、サービスインテントの結果、移動するサービスクラス内の結果(onCreate、onDestroy、anyおよびallメソッド)。 – Zoe

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> 
+1

Androidのサービスに関するすべてのことを学ぶための最良の例http://coderzpassion.com/implement-service-android/遅くて申し訳ありません –

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" /> 

+7

アクティビティとサービスを同じパッケージに残してもパフォーマンスはどれくらい改善されますか?以前は聞いたことがありません。 – OneWorld

+0

おそらく、実行速度に関してではなく、非常に曖昧な緩やかな意味でのパフォーマンスを意味しましたか? –

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"/> 
関連する問題