Keep working even if the application is closed.

I am implementing a service to receive push notifications on an Android device. Notifications will be successfully received when the application is in the foreground. When the application is closed and its instance is cleared from the task manager, notifications are not accepted.

I want the service to work all the time, and it should not stop even if the application is cleared from the task manager.

I start the service from my activity with the click of a button. When I click the button that my service launches, it gives me a Toast notification every minute, but if I click the "Back" button, my service will also be started, but as soon as I remove my application from the last list of actions that appears when the home button is printed for a long time, my service is stopped, and if I run the application again and check the status of the service, but it does not work.

I want my service to start even if my application is closed.

This is my activity class.

package com.example.hello;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    Button btnSer;
    int Pointer=0;
    ListView lv;
    ArrayList<String> alist=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSer=(Button) findViewById(R.id.btnstart);
        btnSer.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                //start  the service when the button is clicked
                Log.e("","status of service : "+isMyServiceRunning(MyService.class));
                //if(!isMyServiceRunning(MyService.class))
                    startService(new Intent(getApplicationContext(), MyService.class));
            }
        });

    }

    //check if the service is running
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


}

This is my class of service.

 package com.example.hello;

import java.util.Calendar;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service{

    private Handler handlerList = new Handler(); 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        Toast.makeText(getApplicationContext(), "On start command called", Toast.LENGTH_LONG).show();
         return Service.START_STICKY;
    }
    public void updateLists(){
        handlerList.postDelayed(mUpdateListTask, 1000*60);
    }
    private Runnable mUpdateListTask = new Runnable() {
        public void run() {  //will make a toast notification every 1 minute.
            Calendar cal = Calendar.getInstance();

            Log.e("","Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":");
            Toast.makeText(getApplicationContext(), "Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":", Toast.LENGTH_LONG).show();
           handlerList.postDelayed(this, 1000*60);
        }};
    @Override
    public void onCreate() {

        updateLists();
        Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
        Log.d("", "onCreate in service");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d("", "onStart in service");    
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
        Log.d("", "onDestroy in service");
    }
}

also added permission in the manifest file

<uses-permission android:name="android.permission.WAKE_LOCK" />
+4
source share
1 answer

startforeground(intent name) onstartCommand().

0

Source: https://habr.com/ru/post/1544509/


All Articles