Android实战Service BroadcastReceiver与AlarmManager
2010-08-22 04:48:00 来源:WEB开发网SleepMusicService.class);
//停止服务
stopService(sleepMusicService);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ...... 代码省略
// 获取Layout中的按钮
startButton = (Button) findViewById(R.id.b_start);
cancelButton = (Button) findViewById(R.id.b_cancel);
startButton.setOnClickListener(startButtonClickListener);
cancelButton.setOnClickListener(cancelButtonClickListener);
restartButton = (Button) findViewById(R.id.b_restart);
restartButton.setOnClickListener(restartButtonClickListener);
}
}
完成了这个Activity之后,就容易的多了,剩下的就是BroadcastReceiver了,新建一个类继承BroadcastReceiver
并且实现onReceive()方法
package com.shinestudio.sleepMusic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "时间到", Toast.LENGTH_SHORT).show();
}
}
当Service中的AlarmManager完成计时后将广播消息给AlarmReceiver,这样就会显示Toast给用户了。
在AndroidManifest.xml中添加activity、service、和receiver的设置
package="com.shinestudio.sleepMusic" android:versionCode="1"
android:versionName="1.0">
android:theme="@android:style/Theme.Black.NoTitleBar">
附加提供的一点点代码片
打开HTC HERO 自带的HTC Music Player
赞助商链接