【问题标题】:IntentService with AlarmManager带有 AlarmManager 的 IntentService
【发布时间】:2015-10-09 05:45:37
【问题描述】:

我想每 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);
    }
}

【问题讨论】:

  • @MikeM。是的,我注册了 `'
  • @MikeM。没有 android:minSdkVersion="11"

标签: android alarmmanager android-pendingintent android-intentservice


【解决方案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>

【讨论】:

  • 我在哪里添加这个 Runnable?在我的 start() 方法中?
  • 你什么时候调用start()方法??
  • 我在 onCreate 中调用了它
  • 然后您可以在onCreate()start() 方法中编写此代码。
  • 我在 start() 方法和 onCreate 中都试过了,但它仍然不起作用。如果 IntentService 启动,它将显示一个 Toast。但是没有显示 Toast。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多