1

我想每10秒重新啓動我的IntentService(它處理HTTP POST請求)。我嘗試使用AlarmManager和PendingIntent作爲每個帖子中描述的。但我的IntentService不啓動。我無法找到任何理由,所以任何幫助,將不勝感激。帶警報管理器的IntentService

IntentService 

public class MyService extends IntentService{ 

    public MyService() { 
     super("MyService"); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     // TODO Auto-generated method stub 
     Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show(); 
     System.out.println("Service Started"); 
     // POST request code here 
    } 
} 

MainActivity 

public class MainActivity extends Activity { 

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

    public void start() { 
     Intent intent = new Intent(this, MyService.class); 
      intent.putExtra("com.hybris.proxi.triggerTime", 5000); 
      PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); 
      long trigger = System.currentTimeMillis() + (5*1000); 
      AlarmManager am =(AlarmManager)getSystemService(Context.ALARM_SERVICE); 
      am.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent); 
    } 
} 
+0

@MikeM 。是的,我註冊了像「<服務android:name =」。MyService「/>' –

+0

@MikeM。沒有android:minSdkVersion =「11」 –

回答

1

您可以使用此代碼:

final Handler handler = new Handler(); 

     TimerTask timertask = new TimerTask() { 
      @Override 
      public void run() { 
       handler.post(new Runnable() { 
        public void run() { 
         startService(new Intent(getApplicationContext(), 
           MyService.class)); 
        } 
       }); 
      } 
     }; 
     Timer timer = new Timer(); 
     timer.schedule(timertask, 0, 10000); 
     } 

這將在10秒

同樣的時間間隔執行,添加您的服務類來體現:

 <service 
      android:name=".MyService" 
      android:enabled="true" > 
     </service> 
+0

在哪裏添加此Runnable?在我的start()方法? –

+0

你什麼時候調用start()方法? – Jas

+0

我在onCreate –