带有 AlarmManager 的 IntentService

IntentService with AlarmManager

我想每 10 秒重新启动我的 IntentService(处理 HTTP POST 请求)。我尝试使用每个帖子中描述的 AlarmManager 和 PendingIntent。但是我的 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);
    }
}

您可以使用此代码:

 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 秒的间隔执行

此外,将您的服务 class 添加到清单中:

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