第 1 部分持久性前台 android 服务,由 UI 启动,也可在睡眠模式下工作,也可在手机重启时启动 [英] part-1 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart

查看:21
本文介绍了第 1 部分持久性前台 android 服务,由 UI 启动,也可在睡眠模式下工作,也可在手机重启时启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

状态:---同样接受 Karakuri 和 Sharad Mhaske 的回答,但自从 Sharad Mhaske 回答之后> 赏金开始,赏金应该给他.

Status:--- I equally accept Karakuri's and Sharad Mhaske's answer, but since Sharad Mhaske answer after the start of bounty, the bounty should go to him.

第 2 部分制作:part-2 持久化前台 android 服务,由 UI 启动,也可以在睡眠模式下工作,也可以在手机重启时启动

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

In stack overflow, only one answer may be accepted. I see both answers as acceptable but one has to be chosen (I chosed at random).

观看者邀请支持/反对投票答案/问题感谢他们的努力!.我赞成 Karakuri 的回答以补偿声誉.

Viewers are invited to up/down vote answers/question to appreciate the effort!. I upvoted Karakuri's answer to compensate reputation.

场景:---

  1. 我想让用户点击开始/停止按钮并从 UI 活动开始/停止服务.我已经制作了 UI,所以不关心这个.但只是按钮点击事件的逻辑.

  1. I want to make the user click a start/stop button and start/stop a service from UI activity. I have made the UI so dont care about that. But Just the logic of the Button click event.

不要希望服务绑定到 UI 活动.如果活动关闭,服务应继续运行.

Do not want the service to be bound to the UI activity. If activity closes, the service should keep running.

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

Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)

除非停止按钮被我的应用程序用户界面点击不希望它被停止(或应该重新启动)即使android回收内存.我和电话用户都知道/将知道它.服务是最重要的.即使在睡觉.

Unless the stop button is clicked by my apps UI, do not want it to be stopped (or should restart itself) Even if android reclaim memory. I and the user of the phone, both are/will be aware of it. The service is most of importance. Even at sleep.

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

details= my app do some operations, sleep for user provided time (15 minuts usually), wakes and perform operations again. this never ends)

如果我需要AlarmManager,如何实现?或任何其他方式?或者只是将操作放在一个永无止境的while 循环中并在最后休眠 15 分钟?

If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?

服务启动时(通过单击启动按钮).它应该进行输入,以便如果手机重启,它会自动启动.

When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.

问题:---

主要问题:

  1. 只是无法获得针对该场景的最佳策略...而且还坚持使用一小段代码,使用哪一个以及如何使用.

  1. Just can't get an optimal strategy for the scenario... and also stuck on small bits of code, which one to use and how.

从 stackoverflow.com 的问题、developer.android.com 和一些谷歌结果中收集了一些零碎的东西,但无法在集成中实施.

Gathered bits and pieces from stackoverflow.com questions, developer.android.com and some google results but cannot implement in integration.

请阅读请求部分.

第二个问题:

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

研究与编码:---

策略:

            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 - 为服务实现 startForeground? 指向答案 1,示例代码.

Android - implementing startForeground for a service? pointing answer 1, example code.

尝试在 Android 启动时启动服务

Android:启动时启动服务?

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 我的研究起点

请求:---

我认为这个问题对于大多数与服务打交道的人来说是一种正常的做法.在那个愿景中,请仅在您有场景经验并且能够以最大示例代码作为完整版本全面解释方面和策略的情况下回答> 所以这也会对社区有所帮助.

I think this question is a normal practice for most people who are dealing with services. In that vision, please only answer if you have experience in the scenario and can comprehensively explain the aspects and strategy with maximum sample code as a complete version so it would be a help to the community as well.

对答案进行投票(负责任地),因为这对我来说很重要,他们分享了他们的观点、时间和经验并帮助了我和社区.

Vote up and down (with responsibility) to the answers as it matters to me who shared their views, time and experience and helped me and the community.

推荐答案

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

答案:您需要使用 START_STICKY Intent 标志启动服务.

Answer:you need to start service with using START_STICKY Intent flag.

@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,以便完成某项任务后的时间.//在服务中注册警报管理器.

Answer:you need to register alarmmanager within service for the time after to some task. //register alarm manager within service.

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);

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

//now have a broadcastreceiver to receive this intent.

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

//在清单中注册这个类以进行警报接收器操作.

//register this class in manifest for alarm receiver action.

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

答案:使用广播接收器监听启动完成的意图.

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 注册此接收器希望这可以帮助你清理事情:)

//need to register this receiver for Action_BOOTCOMPLETED intent in manifest.xml file Hope this helps you clear out things :)

这篇关于第 1 部分持久性前台 android 服务,由 UI 启动,也可在睡眠模式下工作,也可在手机重启时启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆