我是Android开发人员的新手,如果有人可以通过一些示例代码向我解释服务,报警管理器和广播接收器之间的关系,我将非常感谢。我正在开发一个Android应用程序,我需要每10分钟执行一部分代码。此外,我想确保我的应用程序不会被Android操作系统杀死,如果由于电话空间不足等原因而被杀,那么我的应用程序应该重新开始(当然是从同一个地方开始)用户离开的地方)。此外,当手机重新启动时,应该再次启动应用程序。
任何帮助都将受到高度赞赏。谢谢。
答案 0 :(得分:0)
以下是设置警报的完整代码
public class Alarmset extends Activity implements OnClickListener{
Button set;
TimePicker timepicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarmset);
set=(Button) findViewById(R.id.set);
set.setOnClickListener(this);
timepicker = (TimePicker)findViewById(R.id.timepicker);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==set)
{
Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR);
int m = c.get(Calendar.MONTH);
int d = c.get(Calendar.DAY_OF_MONTH);
c.set(y,m,d,timepicker.getCurrentHour(),timepicker.getCurrentMinute(),00);
setAlarm(c);
}
private void setAlarm(Calendar targetCal){
Intent intent = new Intent(getBaseContext(), My.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Alarmset.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
Now Reciever Class
public class MyReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Do Your Stuff here
}
Xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mainmenu.Alarmset"
>
<Button
android:id="@+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/timepicker"
android:layout_below="@+id/timepicker"
android:layout_marginTop="62dp"
android:text="Set"
android:textStyle="bold" />
<TimePicker
android:id="@+id/timepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>