您的位置:首页 > 其它

AlarmManager与PendingIntent的联合使用(二)

2014-02-28 20:44 281 查看
PendingIntent.getService配合AlarmManager,自定义个类继承Service:

package com.example.alarmmanager;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
public IBinder onBind(Intent intent) {
return null;
}

public void onCreate()
{
Log.d("MyService", "onCreate");
super.onCreate();
}

public void onStart(Intent intent, int startId) {
Log.d("MyService", "onStart");
super.onStart(intent, startId);
}

public void onDestroy() {
Log.d("MyService", "onDestroy");
super.onDestroy();
}

}


将sevice类配置到Manifeset文件中:
<service
android:enabled = "true"
android:name = ".MyService">
</service>

添加按钮触发的事件:
Button btnService = (Button)findViewById(R.id.btnService);
btnService.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, MyService.class);
PendingIntent pi = PendingIntent.getService(MainActivity.this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
long time = System.currentTimeMillis();
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pi);
Log.d("btnService", "onClick");
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: