Bootstrap

android定时广播 定时任务 问题


定时的参数及方法说明可参考此文章

http://blog.csdn.net/bingshushu/article/details/50433643


个人遇到的问题:

用 AmarmManager启动服务没有反应,但启动广播可以。广播再去启动服务

广播一定要配置

<intent-filter> <action android:name="com.bignerdranch.android.test.MyAlarmBroadCast" /> </intent-filter>

否则启动广播会失败


代码

public void DingShi(Context context){

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);//获取AlarmManager实例

        int anHour =  4 * 1000 ;  // 6秒

        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;

        Intent intent2 = new Intent(context, AlarmReceiver.class);

        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent2, 0);

        manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),anHour, pi);//开启提醒
    }


广播代码

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "收到定时广播", Toast.LENGTH_SHORT).show();
        Intent i = new Intent(context, RSSPullService.class);
        context.startService(i);
    }

}

服务代码

public class RSSPullService extends IntentService {
    private static final String TAG = "RSSPullService";

    public RSSPullService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        Log.i("服务","服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务服务");
    }


}


AndroidManifest.xml 配置

<service android:name=".RSSPullService"/>

        <receiver android:name=".AlarmReceiver">
            <intent-filter> <action android:name="com.bignerdranch.android.test.MyAlarmBroadCast" /> </intent-filter>
        </receiver>



;