я сделал приложение-напоминание, используя AlarmManager & BroadcastReceiver.дата и время извлекаются из базы данных в реальном времени.и я использую startForegroundService для запуска уведомления и тревоги на фоне также при блокировке устройства.но у меня есть проблема, когда уведомление и сигнал тревоги запускают приложение на устройстве с показом всплывающего диалога.Кто-нибудь может предложить мне, что я должен сделать / заменить в моих кодах?
AlarmReceiver.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import static android.support.v4.content.ContextCompat.startForegroundService;
import static android.support.v4.content.WakefulBroadcastReceiver.startWakefulService;
public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive( Context context, Intent intent) {
// this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startForegroundService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmService.java
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import static android.support.v4.content.ContextCompat.startForegroundService;
import java.util.Random;
import id.restabayu.clientsatu.Classified;
import id.restabayu.clientsatu.DetailActivity;
import id.restabayu.clientsatu.R;
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
// public Classified cl;
@Override
public void onHandleIntent(Intent intent) {
showNotification("PENGINGAT !", "Acara Segera Dimulai ! Silahkan Mempersiapkan Diri");
/* String[] datas = {cl.getNama(), cl.getTanggal(), cl.getWaktu(), cl.getTempat(), cl.getDeskripsi(), cl.getNotif()}; // replace and send your data from here
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
getIntentt(datas), 0); */
}
private Intent getIntentt(String[] data) {
Intent i = new Intent(this, DetailActivity.class);
i.putExtra("NAMA_KEY",data[0]);
i.putExtra("TANGGAL_KEY",data[1]);
i.putExtra("WAKTU_KEY",data[2]);
i.putExtra("TEMPAT_KEY",data[3]);
i.putExtra("DESKRIPSI_KEY",data[4]);
i.putExtra("NOTIF_KEY" , data[5]);
return i;
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
Toast.makeText(this, "Alarm Notif Show", Toast.LENGTH_LONG).show();
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DetailActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher_background)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
private void showNotification(String title, String body) {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DetailActivity.class), 0);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "id.restabayu.clientsatu.test";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,"Notification",NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("IK Channel");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
notificationChannel.enableLights(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title)
.setContentText(body)
.setContentInfo("info")
.setContentIntent(contentIntent);
notificationManager.notify(new Random().nextInt(),notificationBuilder.build());
}
}
DetailActivity.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.Calendar;
import java.util.Date;
import java.lang.String;
import id.restabayu.clientsatu.Service.AlarmReciever;
import id.restabayu.clientsatu.Service.Converter;
import id.restabayu.clientsatu.Service.AlarmService;
public class DetailActivity extends AppCompatActivity {
TextView namaTxt,tanggalTxt,waktuTxt,tempatTxt,deskripsiTxt,notifTxt;
AlarmManager alarmManager;
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
namaTxt = (TextView) findViewById(R.id.namaDetailTextView);
tanggalTxt = (TextView) findViewById(R.id.tanggalDetailTextView);
waktuTxt = (TextView) findViewById(R.id.waktuDetailTextView);
tempatTxt = (TextView) findViewById(R.id.tempatDetailTextView);
deskripsiTxt = (TextView) findViewById(R.id.deskripsiDetailTextView);
notifTxt = (TextView) findViewById(R.id.notifTxt);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
//GET INTENT
Intent i = this.getIntent();
//RECEIVE DATA ngangggo iki raiso dibukak.
String nama = i.getExtras().getString("NAMA_KEY");
String tanggal = i.getExtras().getString("TANGGAL_KEY");
String waktu = i.getExtras().getString("WAKTU_KEY");
String tempat = i.getExtras().getString("TEMPAT_KEY");
String deskripsi = i.getExtras().getString("DESKRIPSI_KEY");
String notif = i.getExtras().getString("NOTIF_KEY");
//BIND DATA
namaTxt.setText(nama);
tanggalTxt.setText(tanggal);
waktuTxt.setText(waktu);
tempatTxt.setText(tempat);
deskripsiTxt.setText(deskripsi);
notifTxt.setText(notif);
}
public void onToggleClicked (View view) {
String date = Converter.ConvertDate(tanggalTxt.getText().toString(), "dd/MM/yyyy", "yyyy MM dd");
String time = notifTxt.getText().toString();
String dateTime = date + " " + time;
Date txtAlarm = Converter.toDate(dateTime, "yyyy MM dd HH:mm");
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.setTime(txtAlarm);
Intent myIntent = new Intent(this, AlarmReciever.class);
pendingIntent = PendingIntent.getBroadcast(DetailActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
else {
alarmManager.cancel(pendingIntent);
Log.d("MyActivity", "Alarm Off");
}
}
}
Logcat
12-24 17:08:58.492 9233-9233/id.restabayu.clientsatu E/AndroidRuntime: FATAL EXCEPTION: main
Process: id.restabayu.clientsatu, PID: 9233
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1769)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6499)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)