问题描述
我正在构建一个简单的提醒应用程序,它将提醒您您的事件。
我刚刚将“警报管理器”与“广播接收器”一起使用,以在将来的某个时间触发我的服务。该服务的目的是在通知到达时振动设备。通知工作正常,但服务未按预期运行。我知道我可以简单地将振动代码放入“广播接收器”中,但需要了解该服务。不知道我的代码有什么问题,提前谢谢我。
广播接收器如下:
public class NotificationSetter extends broadcastReceiver {
@Override
public void onReceive(Context context,Intent intent) {
Log.d("AlarmTriggered","Alarm is triggered to start background service");
Intent serviceVibes = new Intent(context,BackgroundService.class);
context.startService(serviceVibes);
Toast.makeText(context,String.valueOf(Build.VERSION.SDK_INT),Toast.LENGTH_SHORT).show();
//creating the Notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"Notify");
builder.setSmallIcon(R.drawable.reminder);
builder.setContentTitle("Reminding of your event");
builder.setContentText("Time to play Cricket");
builder.setAutoCancel(true);
notificationmanagerCompat compat = notificationmanagerCompat.from(context);
compat.notify(3000,builder.build());
}
}
我的服务等级:
public class BackgroundService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
Log.d("ServiceStarted","Service is started using NotificationSetter");
Vibrator vibes = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
vibes.vibrate(VibrationEffect.createOneshot(2000,200));
}else {
vibes.vibrate(2000);
}
Toast.makeText(getApplicationContext(),Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.remindme">
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:name="com.example.remindme.MyContext"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".StopAlarm"></activity>
<activity android:name=".GetEvent" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.remindme.BackgroundService"
android:enabled="true"
android:exported="true">
</service>
<receiver android:name=".NotificationSetter"
android:enabled="true"
android:exported="true"/>
</application>
</manifest>
解决方法
根据文档,自从之后的Android 8.0开始,除非在以下情况下,否则应用程序无法启动前台服务: https://developer.android.com/about/versions/oreo/background
检查在前台运行应用程序时是否触发了服务,这意味着您的应用程序对用户可见。如果在这种情况下可以正常工作,则意味着您的问题出在Android 8.0中引入的后台执行限制。因此,要使您的服务正常工作,您可以通过调用以下代码行将其作为前台服务启动:
ContextCompat.startForegroundService(context,new Intent(context,YourBackgroundService.class));
前台服务需要在状态栏中显示通知。您可以获取警报通知的实例并将其用作前台服务通知,也可以创建新的通知。