我在android-studio应用程序上发出警报时遇到了一些麻烦。首先,我有一个方法,使用按钮(onClick)调用,然后我在此创建alarmManager,并尝试调用类AlarmReceiver来响铃。问题是程序运行永远不会进入我的AlarmReceiver类,我不明白为什么。我来告诉你代码:
public void sendMessage(View v) {
long time = currentTimeMillis();
Toast.makeText(this, "ALARM ON", Toast.LENGTH_SHORT).show();
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 58);
Toast.makeText(MainActivity.this, "bjr", Toast.LENGTH_SHORT).show();
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pendingIntent);}
这是单击按钮时调用的方法,现在这是AlarmReceiver:
public class AlarmReceiver extends WakefulBroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
因此,当我运行应用程序时,然后单击按钮,打印“ALARM ON”和“bjr”字样,但是AlarmReceiver中的文字“Alarm!Wake up!”永远不会打印,所以应用程序永远不会进入这个类,我需要知道为什么。
我的机器人清单:
`<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.beantunes.myapplication">
<uses-feature
android:name="android.hardware.sensor.accelerometer"
android:required="true"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".vue.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".vue.AlarmReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<activity android:name=".vue.DisplayMessageActivity"></activity>
</application>
`