Android调度任务在应用程序安装时在后台运行

时间:2014-01-02 08:09:13

标签: android service repeat

我正在尝试创建一个任务,每天凌晨1点发送通知。即使应用程序关闭,任务也应该运行。

我已经使用Service和AlarmManager来完成这项工作。但问题是任务执行一次,每当应用程序启动时。我猜这个服务因资源分配而被杀死。

我的问题是如何实现计划任务以保持工作并激活自己,即使它被杀死,以及如何在安装应用程序时获取任务计划。目前,我将启动作为主要活动。

以下是代码中的一小段内容:感谢您对此提供的任何帮助:

public class MyAlarmService extends Service{

     private NotificationManager mManager;

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

    @Override
    public void onCreate(){
       // TODO Auto-generated method stub  
       super.onCreate();
    }


    @Override
    public int onStartCommand(final Intent intent, final int flags,
            final int startId) {


       mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),TabsFragmentActivity.class);
       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,
                                                                PendingIntent.FLAG_UPDATE_CURRENT );
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = " Here is the share content body";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);

       PendingIntent pendingIntent =PendingIntent.getActivity(this, 0,Intent.createChooser(sharingIntent, getResources().getString(R.string.choose_share_action)), 
                                                                PendingIntent.FLAG_UPDATE_CURRENT);


       String msgText = "Notification long text example!! "
                + "where you will see three different kind of notification. "
                + "you can even put the very long string here.";


       int icon = R.drawable.ic_launcher;

          Builder builder = new Notification.Builder(this);
          builder.setContentTitle(getResources().getString(R.string.noticifcation_content_title))
            .setContentText("This is the compact version")
            .setContentIntent(pendingNotificationIntent)
            .setTicker(getResources().getString(R.string.noticifcation_ticker))
            .setSmallIcon(icon)
            .setAutoCancel(false)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .addAction(R.drawable.ic_action_share, 
                    getResources().getString(R.string.share),pendingIntent);
          Notification notification = new Notification.BigTextStyle(builder)
            .bigText(msgText).build();

          mManager.notify(0, notification);

    }

接收器:

public class MyReceiver extends BroadcastReceiver{

    @Override
     public void onReceive(Context context, Intent intent)  {

       Intent service = new Intent(context, MyAlarmService.class);
       context.startService(service);

     }
}

private void createNotification() {
        Calendar calendar = Calendar.getInstance();   

        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.AM);

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

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES , pendingIntent); 
    }

3 个答案:

答案 0 :(得分:0)

当应用程序变为现实时,您需要做的就是扩展Application课程并在onCreate开始您的服务。

class MyApplication extends Application {

  @Override
  public void onCreate() {
    Intent service = new Intent(MyApplication.this, MyAlarmService.class);
    startService(service);
  }
}

答案 1 :(得分:0)

你已经确定了执行一段代码的时间(间隔),最好使用AlarmManager,因为它更节能。 如果您的应用需要收听某种事件,那么服务就是您所需要的。 此代码每15分钟运行一次后台任务,即使应用程序未运行

public static void registerAlarm(Context context) {
     Intent i = new Intent(context, YOURBROADCASTRECIEVER.class);

     PendingIntent sender = PendingIntent.getBroadcast(context,REQUEST_CODE, i, 0);

     // We want the alarm to go off 3 seconds from now.
     long firstTime = SystemClock.elapsedRealtime();
     firstTime += 3 * 1000;//start 3 seconds after first register.

     // Schedule the alarm!
     AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
     am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
                     600000, sender);//10min interval

}

答案 2 :(得分:0)

您必须实施BOOT_COMPLATE Receiver。

当你的应用程序首次启动服务时,如果服务已经运行,那么什么都不做。

您还可以使用其他操作check service is running或不喜欢媒体扫描程序