Java 安卓:AlarmManager不会被解雇
我正在尝试在将来的预定时间生成警报。下面是代码 MainActivity.javaJava 安卓:AlarmManager不会被解雇,java,android,android-service,alarmmanager,android-broadcastreceiver,Java,Android,Android Service,Alarmmanager,Android Broadcastreceiver,我正在尝试在将来的预定时间生成警报。下面是代码 MainActivity.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionB
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.GregorianCalendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void scheduleAlarm(View V)
{
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+60*60*1000;
// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers and
//we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
Intent intentAlarm = new Intent(this, AlarmReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
}
}
public class AlarmReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
// here you can start an activity or service depending on your need
// for ex you can start an activity to vibrate phone or to ring the phone
String message="Hi I will be there later, See You soon";// message to send
// Show the toast like in above screen shot
Log.d("Alarm",message);
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
}
}
AlarmReceiver.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.GregorianCalendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void scheduleAlarm(View V)
{
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+60*60*1000;
// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers and
//we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
Intent intentAlarm = new Intent(this, AlarmReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
}
}
public class AlarmReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
// here you can start an activity or service depending on your need
// for ex you can start an activity to vibrate phone or to ring the phone
String message="Hi I will be there later, See You soon";// message to send
// Show the toast like in above screen shot
Log.d("Alarm",message);
Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
}
}
content_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center_vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/textView1"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Alarm Manager Example"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_marginTop="25dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Schedule The Alarm"
android:onClick="scheduleAlarm"/>
</LinearLayout>
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="voice1.xxx.com.alarmcheck2" >
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReciever"/>
</application>
</manifest>
我试图在一分钟后发出警报,但不幸的是什么也没有发生。我做错了什么?另外,我如何确保我的日程表在手机重新启动/关闭然后打开后仍能正常工作?我想您没有在上面代码的任何地方调用scheduleAlarm()方法。即使在手机重新启动/关闭后,为了安排工作,您也必须收听启动完成事件。对于listen bootcompile,代码如下所示:- 您需要在清单中定义一个接收者,操作名为android.intent.action.BOOT\u
<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
我认为您没有在上述代码的任何地方调用scheduleAlarm()方法。即使在手机重新启动/关闭后,为了安排工作,您也必须收听启动完成事件。对于listen bootcompile,代码如下所示:- 您需要在清单中定义一个接收者,操作名为android.intent.action.BOOT\u
<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
我尝试了你的代码并做了一些调整,它对我有效
public void scheduleAlarm() {
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final PendingIntent wakeupIntent = PendingIntent.getBroadcast(this, 0,
new Intent(this, AlarmReciever.class), PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency = 6* 1000; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, wakeupIntent);
}
试试这个。我尝试了你的代码并做了一些调整,它对我很有用
public void scheduleAlarm() {
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final PendingIntent wakeupIntent = PendingIntent.getBroadcast(this, 0,
new Intent(this, AlarmReciever.class), PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency = 6* 1000; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, wakeupIntent);
}
试试这个。您是否在清单中注册了收件人?另外,
60*60*1000
毫秒是一小时。@MikeM:对不起,我现在已经发布了清单。我是新手,所以我做了,但不确定是否正确。我正在编辑我的评论。您可能需要刷新页面。如果您正在测试,您可能只想现在设置时间。@MikeM:谢谢,它确实起作用了。另外,我如何将时间设置为7月1日上午9:30,并确保闹钟正常工作?(您知道,用户将打开和关闭手机,他不会将手机保持在forerver上,因此如何解决此问题?)如果重新启动手机,则使用alarm manager设置的报警将重置。因此,您可能需要注册一个接收器以完成引导并从onReceive再次设置警报。您是否在清单中注册了接收器?另外,60*60*1000
毫秒是一小时。@MikeM:对不起,我现在已经发布了清单。我是新手,所以我做了,但不确定是否正确。我正在编辑我的评论。您可能需要刷新页面。如果您正在测试,您可能只想现在设置时间。@MikeM:谢谢,它确实起作用了。另外,我如何将时间设置为7月1日上午9:30,并确保闹钟正常工作?(您知道,用户将打开和关闭手机,他不会将手机保持在forerver上,因此如何解决此问题?)如果重新启动手机,则使用alarm manager设置的报警将重置。因此,您可能需要注册一个接收器以完成引导并从onReceive再次设置警报。在清单中像这样注册您的接收器-
谢谢。通过查看代码,您是否可以建议在收到ServiceStarter
的时在此中包含哪些内容?@PeakGen执行以下操作:-如果(intent.getAction().equalsIgnoreCase(intent.ACTION\u BOOT\u COMPLETED)){//您的代码………}
我不清楚,您的意思是我必须将scheduleAlarm()
中的代码移动到OnReceive()
?我现在不考虑您的报警接收器写入,我共享的代码是在手机重新启动/关闭后执行任何操作,然后再打开。在清单中像这样注册您的接收器-
谢谢。通过查看代码,您是否可以建议在收到ServiceStarter
的时在此中包含哪些内容?@PeakGen执行以下操作:-如果(intent.getAction().equalsIgnoreCase(intent.ACTION\u BOOT\u COMPLETED)){//您的代码………}
我不清楚,您的意思是我必须将scheduleAlarm()
中的代码移动到OnReceive()
?我现在不想写您的闹钟接收器,我共享的代码是在手机重新启动/关闭后再打开后执行任何操作