android - 我需要确保 Android 服务在一年内每天运行一次

标签 android service notifications

我有一个简单的应用程序,它每天通过通知向用户发送一次励志名言。单击通知时,用户将转到显示报价的 Activity 。

主要 Activity 没有图形用户界面,它启动 Serv1 然后调用 finish()。 word1 类非常简单,它有一个引号的字符串数组,它检查一年中的第几天,然后转到该索引并显示引号。

我认为 Android 系统几乎可以在需要更多内存时随时杀死它想要的任何东西。我想我的选择可能是

  1. 让它成为用户知道的前台服务,因此系统不会选择终止它?

  2. 使用启动粘滞,我在设置->开发选项->进程统计中检查了我的手机,我看到 Serv1 运行了大约 4 天,但今天它不在那里。是否有系统保留的启动粘性列表?从它被杀死到它重新启动之间的时间间隔。也就是说,如果我在 m 代码中正确使用它。

  3. 或者让它定期打开?通过检查它是否正在运行的 broadcastReciever。这是它变得有点模糊的地方,如果它被杀死怎么办?

我是 Android 的新手,所以任何帮助都会很棒...

public class Serv1 extends Service {

private PendingIntent pendingIntent;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate();
}

public int onStartCommand(Intent intent, int flags, int startId) {
    Calendar calendar = Calendar.getInstance();

    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 18);
    calendar.set(Calendar.MINUTE, 18);

    Intent myIntent = new Intent(Serv1.this, MyReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(Serv1.this, 0, myIntent, 0);

    AlarmManager alarmManager = (AlarmManager) this
            .getSystemService(ALARM_SERVICE);

    alarmManager.setInexactRepeating(AlarmManager.RTC,
            calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            pendingIntent);
    return START_REDELIVER_INTENT;
}

public class MyReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
 (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
 Intent service1 = new Intent(context, MyAlarmService.class);
 context.startService(service1);

}

public class MyAlarmService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
  }


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, startId, startId);

    Intent intent1 = new Intent(this.getApplicationContext(), Word.class);
    PendingIntent showWord = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setTicker("Daily Word").setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Daily Word")
            .setContentText("Your Word is ready")
            .setContentIntent(showWord).setAutoCancel(true).build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(0, notification);
    stopSelf();

    return START_REDELIVER_INTENT;
    }
  }

最佳答案

试试这个:

public class RefreshService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

     private AudioManager mAudioManager;
private DbAdapter mDbHelper;
private String user = null;
private String pass = null;

public class RefreshBinder extends Binder {
    RefreshService getService() {
        return RefreshService.this;
    }
}

private static final int MAXIMUM_NOTIFY_EVENTS = 7;

private final IBinder binder = new RefreshBinder();

private final Handler handler = new Handler();

private final Runnable refresher = new Runnable() {
    public void run() {
        refresh();
    }

};

private final Runnable worker= new Runnable() {
    public void run() {
        doWork();
    }

};

private BroadcastReceiver screenOffReceiver;

private boolean screenOn = true;

private BroadcastReceiver screenOnReceiver;

@Override
public IBinder onBind(Intent arg0) {
    Log.i(RefreshService.class.getName(), "onBind");
    return binder;
}

@Override
public void onCreate() {
    super.onCreate();


    screenOnReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("RefreshService", "Screen on");
            refresh();
        }
    };

    registerReceiver(screenOnReceiver, new IntentFilter(
            Intent.ACTION_SCREEN_ON));

    screenOffReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("RefreshService", "Screen off");

        }
    };

    registerReceiver(screenOffReceiver, new IntentFilter(
            Intent.ACTION_SCREEN_OFF));


    scheduleNext();
    scheduleNextPost();
}

@Override
public void onDestroy() {
    Log.i(RefreshService.class.getName(), "onDestroy");
    if (screenOnReceiver != null) {
        unregisterReceiver(screenOnReceiver);
    }
    if (screenOffReceiver != null) {
        unregisterReceiver(screenOffReceiver);
    }
    if (handler != null)
        handler.removeCallbacks(refresher);
}

@Override
public boolean onUnbind(Intent arg) {
    Log.i(RefreshService.class.getName(), "onUnbind");
    return true;
}

public void refreshNext() {

    scheduleNext();

}

public void refresh() {

    Log.i("RefreshService", "Refreshing");

    refreshWidgets();

    scheduleNext();

}

public void doWork() {

    doTheWork();

    scheduleNextPost();

}

private void doTheWork() {

    Log.d("RefreshService", "Refreshing ");


}



/**
 * Note: The point of doing this here is to allow user control over the
 * update frequency
 */
private void refreshWidgets() {

}

private void scheduleNext() {
    final SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(this);


    long defaufaultFrequency = getLong(
                getResources().getText(R.string.refresh_frequency_default)
                        .toString(), 30000);

    handler.postDelayed(refresher, preferences.getLong(getResources()
                .getText(R.string.refresh_frequency_key).toString(),
                defaufaultFrequency));

}

private void scheduleNextPost() {
    final SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(this);


    handler.postDelayed(worker,
                preferences
                        .getLong(
                                getResources().getText(
                                        R.string.post_frequency_key)
                                        .toString(),
                                getLong(getResources().getText(
                                        R.string.post_frequency_default)
                                        .toString(), 30000)));


}



private long getLong(String string, long defaultValue) {
    long number;
    try {
        number = Long.parseLong(string);
    } catch (NumberFormatException e) {
        number = defaultValue;
    }
    return number;
}

private int getInt(String string, int defaultValue) {
    int number;
    try {
        number = Integer.parseInt(string);
    } catch (NumberFormatException e) {
        number = defaultValue;
    }
    return number;
}

protected void processStatus(Integer status) {

}


}

关于android - 我需要确保 Android 服务在一年内每天运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28002421/

相关文章:

Android Gradle 问题 - Flutter/Dart

c# - 为什么 Process.Start 会意外返回 false

java - 在自定义内容通知中使用后更新 RemoteView

android - Plot Projects - 将通知过滤器引入现有应用程序

ios - 使用通知中心在if语句中触发函数

android - 如何在Material Plugin for Sketch中导出生成的主题?

android - 使用导航架构组件在 fragment 中显示备份/备份确认

android - 开发软键盘 - 如何切换 View /服务?

android - 在Android中编写后台服务

android - ADT 22 带 Action 条夏洛克