部分1持久前景的Andr​​oid服务,通过用户界面开始,工作在休眠模式下也一样,也开始在手机重启重启、用户界面、持久、前景

2023-09-05 10:53:24 作者:时间总能抚平一切

状态:--- 我同样接受Karakuri的和沙拉德Mhaske的答案,但由于沙拉德帕Mhaske回答< STRONG>在的开始赏金,赏金应该去他。对

第2发:part-2持续的前景机器人服务,通过用户界面开始,工作在休眠模式下也一样,也开始在手机重启

堆栈溢出,只有一个答案可能是接受。我看到的两个答案为接受但是你必须选择(我chosed随意)。

观众是请 /下的投票答案/问题以AP preciate努力!。我upvoted Karakuri的答案,以弥补名誉。

情景:---

我希望让用户单击开始/停止按钮和启动/停止从UI活动服务。我所做的界面,因此不关心这个。但按钮的Click事件只是逻辑。

你的不可以希望该服务的绑定到用户界面活性。如果活动关闭,该服务应保持运行。

想要让最省力的服务是持续并没有停止在任何情况下。将给予最重,并运行它 ForGroundSerice 为它具有重要的更高层次。(希望这是确定?)

除非停止按钮被点击按我的应用程序的用户界面,不希望它被停止(或应该重新启动本身)即使机器人回收内存。 I和电话的用户,两者都是/将会意识到这一点。这项服务是最重要的。 即使在睡觉。

详细信息=我的应用程序做一些操作,睡的用户提供时间(通常为15分钟再予),醒来后,再进行操作。这永远不会结束)

如果我需要 AlarmManager ,如何实现?或任何其他方式?或者只是把操作的一个永无止境的 while循环和睡眠15分钟再予在结束了吗?

在启动服务(通过点击开始按钮)。使就自动启动,如果手机重新启动它应该使一个条目。

问:---

主要问题:

只是无法获得最优策略作为场景......也停留在code ,小位使用哪一个如何。

聚集的点点滴滴,从stackoverflow.com问题,developer.android.com和一些谷歌的结果,但可以整合无法实现。

请读出的请求栏目

中的问题:

在我的code意见是那些小的问题。

研究与code:---

策略:

 希望这种情况发生在用户打开UI每次。

    //开始按钮:-----
    //检查是否ForGroundService运行与否。如果没有运行,使无功/设置/等serviceStatus为假
            &LT; -------(如何以及在哪里盯着这一点,如下所述布尔?)
    //启动ForGroundService
            &LT; -------(?怎么)
    //使SericeStatus为真

    //检查ServiceStartOnBoot是假的
    //把ForGroundService在启动时自动-------(使它永远启动时,手机重新启动/重新启动)
            &LT; -------(?怎么)
    //使ServiceStartOnBoot为真
            //布尔也可用于检查服务状态。



    //停止按钮:------
    //使SericeStatus和ServiceStartOnBoot为假
    //停止服务,删除的启动项/策略
 

启动活动UI类/停止该服务:

 公共类SettingsActivity延伸活动{

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_settings);

        //这里的一些按钮启动/停止和他们的onClick Listners



    意图mySericeIntent =新的意图(这一点,TheService.class);
    }


    私人无效startMyForGroundService(){

    startService(mySericeIntent);

    }

    私人无效stopMyForGroundSerice(){
        stopService(mySericeIntent);
                          ///////这是一个更好的方法? stopService(新意图(这一点,TheService.class));
                          ///////或进行意向mySericeIntent =新的意图(这一点,TheService.class);
                          ///////,使启动和停止方法使用相同的?

                          ///////如何调用stopSelf()吗?或者还有什么地方?最新最好的方法是什么?
    }

}
 

服务类:

 公共类TheService延伸服务{

      @覆盖
      公众的IBinder onBind(意向为arg0){
          // TODO自动生成方法存根
          返回null;
      }

      @覆盖
        公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
          startForeground(1,新的通知());
                                  //////将尽我所有的东西都基于在方法ONSTART()或onCreat()?

          返回START_STICKY; /////这回是更好地保持服务运行,直到明确地杀害。相反,系统杀死。
                                  ///// http://developer.android.com/reference/android/app/Service.html#START_FLAG_REDELIVERY

          //注意事项: -  //如果实现onStartCommand()安排工作,异步或在另一个线程中完成的,
          //那么你可能想使用START_FLAG_REDELIVERY让系统重新传递一个Intent给你,这样它不会丢失,如果在处理它的服务被杀害
      }

      @覆盖
        公共无效的onDestroy(){
          停止();
        }

      公共无效停止(){
          //如果运行
          // 停止
          //使瓦尔假
          //做一些停止的东西
          stopForeground(真正的);
                                  ///////如何调用stopSelf()吗?或者还有什么地方?最新最好的方法是什么?

      }


  }
 

的Menifest文件:

 &LT; XML版本=1.0编码=UTF-8&GT?;
      &LT;舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
      包=com.example.myapp
      安卓版code =1
      机器人:VERSIONNAME =1.0&GT;

      &LT;用途-SDK
          安卓的minSdkVersion =10
          机器人:targetSdkVersion =17/&GT;

      &LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_FINE_LOCATION/&GT;
      &LT;使用-权限的Andr​​oid:名称=android.permission.INTERNET对/&GT;

      &lt;应用

          机器人:allowBackup =真
          机器人:可调试=真
          机器人:图标=@可绘制/ ic_launcher
          机器人:标签=@字符串/ APP_NAME
          机器人:主题=@风格/ AppTheme&GT;
          &LT;活动
          机器人:名称=com.example.myapp.MainActivity
          机器人:标签=@字符串/ APP_NAME&GT;
          &LT;意向滤光器&gt;
              &lt;作用机器人:名称=android.intent.action.MAIN/&GT;

              &LT;类机器人:名称=android.intent.category.LAUNCHER/&GT;
          &所述; /意图滤光器&gt;
          &LT; /活性GT;
          &LT;活动
          机器人:名称=com.example.myapp.SettingsActivity
          机器人:标签=@字符串/ title_activity_settings&GT;
          &LT; /活性GT;

      &LT; /用途&gt;

      &LT; /舱单&GT;
 

参考:---

Android - 实施startForeground的服务的指点答案1,例如code

Trying在启动时自动在Android

服务

Android的:启动服务在启动

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

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

http://developer.android.com/training/运行后台服务/创建-service.html 没有preffered由我。

http://developer.android.com/guide/components/流程 - 和 - threads.html 研究我的出发点

要求:---

我认为这个问题是大多数谁正在处理的服务的人的常规。 在这一愿景,如果你有经验的情况下,可以融为一体prehensively解释请只回答方面和战略是最大采样code 作为一个< STRONG>完整版所以这将是一个有利于社会也是如此。

投票向上和向下(与责任)的答案,因为它关系到我是谁分享了他们的观点,时间和经验,帮助我和社区。 解决方案

阙:想要让最省力的服务是持久的,在任何情况下不停止。将给予最重,并运行它ForGroundSerice,因为它具有重要的更高层次。 (希望这是确定?)

答:您需要使用START_STICKY意向标志启动服务

  @覆盖
公众诠释onStartCommand(意向意图,诠释标志,诠释startId){

//我们希望这项服务继续运行,直到它被明确
//停止,因此返回粘​​。
返回START_STICKY;
}
 

阙:如果我需要AlarmManager,如何实现?或任何其他方式?或者只是把操作的一个永无止境的while循环和睡眠15分钟再予在结束了吗?

答:您需要为后,一些任务中的时间服务注册alarmmanager。 //在服务注册报警经理。

  PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,新的意向(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);
 

//现在有一个BroadcastReceiver获得这一意图。

 类Alarmreceiver扩展的BroadcastReceiver
{
   // U可以在接收器的onReceive方法任务。
}
 

//清单中的报警接收机行动注册此类。

阙:当服务已启动(通过点击开始按钮)。因此,它自动启动,如果手机重新启动它应该使一个条目。

答:使用广播reciver监听ONBOOT完成意向

 公共类StartAtBootServiceReceiver扩展的BroadcastReceiver {

    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        尝试 {
            如果(android.intent.action.BOOT_COMPLETED.equals(intent.getAction())){

                组件名排版=新单元名(context.getPackageName(),LicensingService.class.getName());
                组件名服务= context.startService(新意图()setComponent(COMP)。);
                如果(空==服务){
                    //东西真的错在这里
                    //Log.Write("Could无法启动服务+ comp.toString(),Log._LogLevel.NORAML);
                }
            }
            其他 {
                //Log.Write("Received意想不到的意图+ intent.toString(),Log._LogLevel.NORAML);
            }
        }赶上(例外五){
            在授权服务器//Log.Write("Unexpected出错:+ e.toString(),Log._LogLevel.NORAML);
        }
    }
}
 

//需要注册这个接收器Action_BOOTCOMPLETED意图manifest.xml文件 希望这可以帮助你清除掉的东西:)

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.

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

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

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

Scenario:---

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.

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

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

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= my app do some operations, sleep for user provided time (15 minuts usually), wakes and perform operations again. this never ends)

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.

QUESTION:---

Primary Question:

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

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

Please read out the Requests Section.

Secondary Question:

The comments in my code are those small questions.

Research and Code:---

Strategy:

            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 class that starts/stops the service:

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?
    }

}

The Service class:

  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?

      }


  }

The Menifest file:

      <?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>

References:---

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

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 not preffered by me.

http://developer.android.com/guide/components/processes-and-threads.html my starting point of research

Requests:---

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: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?)

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: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?

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:When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.

Answer:use broadcast reciver to listen for onboot completed intent.

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

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

 
精彩推荐
图片推荐