WEB开发网
开发学院手机开发Android 开发 Android Broadcast调用Service做的一个定时器 阅读

Android Broadcast调用Service做的一个定时器

 2010-08-20 02:13:00 来源:WEB开发网   
核心提示:b_call_service = (Button) findViewById(R.id.call_alarm_service);b_call_service.setOnClickListener(this);b_exit_service = (Button) findViewById(R.id.exit);b_exit

b_call_service = (Button) findViewById(R.id.call_alarm_service);

b_call_service.setOnClickListener(this);

b_exit_service = (Button) findViewById(R.id.exit);

b_exit_service.setOnClickListener(this);

intent = new Intent(this, AlarmReceiver.class);

p_intent = PendingIntent.getBroadcast(this, 0, intent, 0);

}

public void onClick(View arg0) {

if (arg0 == b_call_service) {

setTitle("Waiting... 5s后Alarm启动");

Calendar calendar = Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());

calendar.add(Calendar.SECOND, 5);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), p_intent);

}

if (arg0 == b_exit_service) {

setTitle("Alarm关闭");

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

am.cancel(p_intent);

}

}

}

Java代码

1. public class AlarmReceiver extends BroadcastReceiver {

2.

3. public void onReceive(Context context, Intent i) {

4. context.startService(new Intent(context, AlarmService.class));

5. }

6. }

public class AlarmReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent i) {

context.startService(new Intent(context, AlarmService.class));

}

}

Java代码

1. public class AlarmService extends Service {

2. public IBinder onBind(Intent intent) {

3. return null;

4. }

5. public void onCreate() {

6. // 只在创建时执行一次

7. }

8. public void onStart(Intent intent, int startId) {

9. // 可执行多次

10. Toast.makeText(this, "hello 土豆", Toast.LENGTH_LONG).show();

Tags:Android Broadcast 调用

编辑录入:coldstar [复制链接] [打 印]
赞助商链接