最近、主人公が何度か(約15分)オフラインになっているテキストベースのゲームをリリースしました。しかし100人中10人近くのユーザーが主人公がオンラインになることはないと不平を言った。私は、次のしているアラームレシーバクラス:私のユーザの中には、私のアラームマネージャが動作しないと不平を言うものがあります。どうして?
public class AlarmReceiver extends BroadcastReceiver {
Context cont;
Notification noti;
@Override
public void onReceive(Context context, Intent intent) {
WakeLocker.acquire(context);
cont = context;
context.sendBroadcast(new Intent("MESSAGE"));
writeWaitTimeAlert("0");
if(!isAppForground(context))
notifyMe();
WakeLocker.release();
}
public void writeWaitTimeAlert(String str) {
try {
FileOutputStream fileOutputStream = cont.openFileOutput("timeBoolean.txt", Context.MODE_PRIVATE);
fileOutputStream.write(str.getBytes());
OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream);
osw.flush();
osw.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isAppForground(Context mContext) {
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
return false;
}
}
return true;
}
public void notifyMe() {
Intent intent = new Intent(cont, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(cont, 0, intent, 0);
noti = new Notification.Builder(cont)
.setTicker("My app")
.setContentTitle("Message")
.setContentText("Hello!")
.setSmallIcon(R.drawable.ic_stat_message)
.setContentIntent(pendingIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm = (NotificationManager) cont.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, noti);
}
}
そして、私は「Playground.class」という名前の別のクラスでsetAlarmを持っている:
public void setAlarm(long time) {
Toast.makeText(context.getApplicationContext(), "Offline!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("alarmId", REQUEST_CODE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
time * 1000, pendingIntent);
}
私を助けたり、私に解決するために他の方法を提案して下さいそれ。ありがとうございました!
BroadReceiverクラスでsetAlarmメソッドを記述する必要はありますか? –
どうしてですか?あなたのケースでは、最良の方法はsetAlarmメソッドから実際にコードを削除し、上記のコードのようにBroadcastReceiverに余計な値でブロードキャストを送信することです。次に、それを意図から取得し、動的パラメータのように使用します。最後に、TimeBroadcastのようなクラスからAlarmReceiverクラスにブロードキャストを送信します。これにより、sendReviewer内のコードがsendBroadcast Intentで渡された時間間隔だけ遅延して実行されます。 – grabarz121
なぜ私のonReceiveメソッドがトリガーしていないのかを知りたいですか?いくつかのアンドロイド携帯電話が私のアラームマネージャーを殺すのですか?何が問題なの?あなたが言ったように私が実装する場合、それは実行コードを保証しますか? –