简体   繁体   English

在后台运行Intent服务

[英]Running Intent Service in Background

I am trying to run intent service in background even if the app is closed and have written this code. 我正在尝试在后台运行Intent服务,即使该应用程序已关闭并已编写此代码。 But the service doesn't runs in the background.Here is my code. 但是该服务没有在后台运行,这是我的代码。

MainActivity.java MainActivity.java

package com.example.h.intentservice;

public class MainActivity extends AppCompatActivity {

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

    public void startService(View view){
        Intent intent = new Intent(this,MyIntentService.class);
        startService(intent);

    }

    public void stopService(View view){
      Intent intent=new Intent(this,MyIntentService.class);
        stopService(intent);
    }
}

MyIntentService.java MyIntentService.java

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("My_Worker_Thread");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this,"Service started",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Stopped",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        synchronized (this){
            int count=0;
            while(count<=10)
            {
                try{
                    wait(1500);
                    count++;
                }
                catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }
}   

First of all an intent service cannot run in the background after closing the application. 首先,关闭应用程序后,意图服务无法在后台运行。 An intentService is run only once and it automatically closes the thread once the task assigned to it is done. intentService仅运行一次,一旦分配给它的任务完成,它就会自动关闭线程。 You will have to use a service for background requests. 您将必须使用一项服务来处理后台请求。 Secondly you have not called the startService() method from the onCreate and therefore the serviceIntent has not been initiated. 其次,您尚未从onCreate调用startService()方法,因此未初始化serviceIntent。 In both the startService() method and the stopService() method you are passing a view which i can see is unused inside the method body. 在startService()方法和stopService()方法中,您都传递了一个视图,我可以看到该视图在方法主体内部未使用。 So therefore i can advice you to adjust your code this way 因此,我可以建议您以这种方式调整代码

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

    startService();

    //here you have started the service intent
    //if you want to stop the same just call stopService()
}

public void startService(){
    Intent intent = new Intent(this,MyIntentService.class);
    startService(intent);

}

public void stopService(){
  Intent intent=new Intent(this,MyIntentService.class);
    stopService(intent);
}

Am also posting sample code for a service that can run in the background. 我还发布了可以在后台运行的服务的示例代码。

Below is sample code for a service 以下是服务的示例代码

public class UploadService extends Service {

 public int counter = 0;

    public UploadService(Context applicationContext) {
        super();

        Log.i("SERVICE", "hService started");
    }

    public UploadService() {
    }

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

        //instantiate your variables here

        //i call my startUpload method here to doing the task assigned to it

        startUpload();

        return START_STICKY;
    }



    public void startUpload() {

    //call the method with your logic here

    //mine is a sample to print a log after every x seconds

        initializeTimerTask();

    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        // timerTask = new TimerTask() {

        //we can print it on the logs as below
        Log.i("in timer", "in timer ++++  " + (counter++));

        //or use the print statement as below
        System.out.println("Timer print " + counter++);

    }

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


      @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM