其他分享
首页 > 其他分享> > 由UI启动的第1部分持久foreGround android服务,也在睡眠模式下工作,也在手机重启时启动

由UI启动的第1部分持久foreGround android服务,也在睡眠模式下工作,也在手机重启时启动

作者:互联网

状态:—我同样接受Karakuri和Sharad Mhaske的回答,但自从Sharad Mhaske在赏金开始后回答,赏金应该归他所有.

第2部分:part-2 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart

在堆栈溢出中,只能接受一个答案.我认为这两个答案都是可以接受的,但必须选择一个(我随机选择).

观众被邀请上/下投票答案/问题,以欣赏努力!我赞成Karakuri的答案来弥补声誉.

场景:—

>我想让用户单击开始/停止按钮并从UI活动启动/停止服务.我已经制作了用户界面,所以不关心它.但只是按钮点击事件的逻辑.
>不希望将服务绑定到UI活动.如果活动关闭,服务应继续运行.
>想要尽最大努力使服务持久并且在任何情况下都不会停止.将它赋予最大的权重并将其作为ForGroundSerice运行,因为它具有更高的重要性层次. (希望没问题?)
>除非我的应用程序用户界面点击了停止按钮,否则不要让它停止(或者应该重新启动)即使android回收内存.我和手机用户都知道了.这项服务至关重要.即使在睡觉.

details =我的应用程序执行一些操作,为用户提供的时间(通常为15分钟)休眠,唤醒并再次执行操作.这永远不会结束)

如果我需要AlarmManager,如何实现?或任何其他方式?或者只是将操作放在一个无休止的while循环中并在结束时睡15分钟?
>启动服务时(通过单击开始按钮).它应该输入一个条目,以便在手机重启时自动启动.

题: – –

主要问题:

>只是无法为场景获得最佳策略……并且还会停留在一小段代码上,哪些代码可以使用以及如何使用.
>来自stackoverflow.com问题,developer.android.com以及一些谷歌搜索结果中的点点滴滴,但无法在集成中实现.
>请读出请求部分.

次要问题:

我的代码中的注释是那些小问题.

研究与代码:—

战略:

            want this to happen every time the user opens the UI.

    //Start Button:-----
    //check if ForGroundService is running or not. if not running, make var/settings/etc "serviceStatus" as false 
            <-------(how and where to stare this and below stated  boolean?)
    //start ForGroundService 
            <-------(how?)
    //make "SericeStatus" as true

    //check if "ServiceStartOnBoot" is false
    //Put ForGroundService to start on boot -------(to make it start when ever the phone reboots/restarts) 
            <-------(how?)
    //make "ServiceStartOnBoot" as true
            // the boolean can also be used to check the service status.



    //Stop Button:------
    //makes SericeStatus and ServiceStartOnBoot as false
    //stops service and deletes the on boot entry/strategy

用于启动/停止服务的Activity UI类:

public class SettingsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        //some button here to start / stop and their onClick Listners



    Intent mySericeIntent = new Intent(this, TheService.class);
    }


    private void startMyForGroundService(){

    startService(mySericeIntent);

    }

    private void stopMyForGroundSerice(){
        stopService(mySericeIntent);
                          /////// is this a better approach?. stopService(new Intent(this, TheService.class));          
                          /////// or making Intent mySericeIntent = new Intent(this, TheService.class);
                          /////// and making start and stop methods use the same?

                          /////// how to call stopSelf() here? or any where else? whats the best way?
    }

}

服务类:

  public class TheService extends Service{

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

      @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
          startForeground(1, new Notification());
                                  ////// will do all my stuff here on in the method onStart() or onCreat()?

          return START_STICKY;    ///// which return is better to keep the service running untill explicitly killed. contrary to system kill.
                                  ///// http://developer.android.com/reference/android/app/Service.html#START_FLAG_REDELIVERY

          //notes:-//  if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, 
          //then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it
      }

      @Override
        public void onDestroy() {
          stop();
        }

      public void stop(){
          //if running
          // stop
          // make vars as false
          // do some stopping stuff
          stopForeground(true);
                                  /////// how to call stopSelf() here? or any where else? whats the best way?

      }


  }

Menifest文件:

      <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.myapp"
      android:versionCode="1"
      android:versionName="1.0" >

      <uses-sdk
          android:minSdkVersion="10"
          android:targetSdkVersion="17" />

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.INTERNET" />

      <application

          android:allowBackup="true"
          android:debuggable="true"
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
          android:name="com.example.myapp.MainActivity"
          android:label="@string/app_name" >
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />

              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
          </activity>
          <activity
          android:name="com.example.myapp.SettingsActivity"
          android:label="@string/title_activity_settings" >
          </activity>

      </application>

      </manifest>

参考文献:—

Android – implementing startForeground for a service?指点答案1,示例代码.

Trying to start a service on boot on Android

Android: Start Service on boot?

http://developer.android.com/guide/components/services.html

http://developer.android.com/reference/android/app/Service.html

http://developer.android.com/training/run-background-service/create-service.html不是我的优先考虑.

http://developer.android.com/guide/components/processes-and-threads.html我的研究起点

要求: – –

我认为这个问题对于大多数处理服务的人来说都是正常的做法.
在该愿景中,请仅回答您是否具有该方案的经验,并且能够以最大样本代码作为完整版本全面解释方面和策略,以便它也将对社区有所帮助.

对答案进行上下(有责任)投票,因为对我而言,他们分享了他们的观点,时间和经验,并帮助我和社区.

解决方法:

Que:想要尽最大努力保持服务的持久性并且在任何情况下都不会停止.将它赋予最大的权重并将其作为ForGroundSerice运行,因为它具有更高的重要性层次. (希望没问题?)

答:您需要使用START_STICKY Intent标志开始服务.

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

// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}

Que:如果我需要AlarmManager,如何实现呢?或任何其他方式?或者只是将操作放在一个无休止的while循环中并在结束时睡15分钟?

答:在完成某项任务后,您需要在服务中注册alarmmanager.
//在服务中注册警报管理器.

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new         Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);

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

    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);

//现在有一个广播接收者来接收这个意图.

class Alarmreceiver extends Broadcastreceiver
{
   //u can to task in onreceive method of receiver.
}

//在清单中注册此类以用于警报接收器操作.

Que:启动服务时(通过单击“开始”按钮).它应该输入一个条目,以便在手机重启时自动启动.

答:使用广播reciver来监听onboot完成的意图.

public class StartAtBootServiceReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        try {           
            if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {                

                ComponentName comp = new ComponentName(context.getPackageName(), LicensingService.class.getName());
                ComponentName service = context.startService(new Intent().setComponent(comp));
                if (null == service){
                    // something really wrong here
                    //Log.Write("Could not start service " + comp.toString(),Log._LogLevel.NORAML);
                }
            }
            else {
                //Log.Write("Received unexpected intent " + intent.toString(),Log._LogLevel.NORAML);   
            }
        } catch (Exception e) {
            //Log.Write("Unexpected error occured in Licensing Server:" + e.toString(),Log._LogLevel.NORAML);
        }
    }
}

//需要在manifest.xml文件中为Action_BOOTCOMPLETED intent注册此接收器
希望这可以帮助你清除事情:)

标签:android,android-intent,android-service,android-alarms,android-backup-service
来源: https://codeday.me/bug/20190930/1837142.html