我正在创建一个简单的应用程序,它包含一天一次弹出通知的服务。我试图通过报警来实现这一点。如果我不关闭应用程序,所有工作都很完美。但是,如果我在触发接收器时关闭应用程序,我会收到消息“应用程序已停止工作”或其他任何内容。
如果没有应用程序或其他活动,服务无法正常工作,我就会徘徊?任何见解?
这是我的代码:
接收者:
public class AlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.ddimitrovd.hap4eapp4e.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MainIntentService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
}
这是服务:
public class MainIntentService extends IntentService {
int noteID = 1;
String chanelID;
public MainIntentService() {
super("MainIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
chanelID = getString(R.string.channel_ID);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
// Do the task here
createNotificationChannel();
popNotif();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
private void popNotif() {
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, chanelID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(noteID, mBuilder.build());
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(chanelID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
我确定警报会触发接收器。
谢谢!
答案 0 :(得分:0)
我认为我发现了这个问题。我认为我的IntentService无法执行复杂,因为BroadcastReceiver进程在它可以执行之前被终止。更多信息here。 我所做的只是在接收器中弹出我的通知,但我想更好的解决方案是启动另一个线程或将其设置为异步。