简体   繁体   中英

How to run intent service even app is killed/destroyed

I am implementing chat based app using IntentService . Now I need to get message even app is not in background. Clearly what I want is I need to run intent service if app is not in background state.

public class ChatService extends IntentService {
JabberSmackAPI c = null;
XMPPConnection connection;

@Override
public void onCreate() {
    super.onCreate();
    System.out.println("chatservice------onCreate-----");

}

@Override
public int onHandleIntent(Intent arg0) {
    System.out.println("--chat services--");
    try {
        setUp(c);
    } catch (XMPPException e) {
        // TODO Auto-generated catch block
        System.out.println("--XMPPConnection error--chat service--");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("--IOException error--chat service--");
        e.printStackTrace();
    }

    return super.onStartCommand(intent, flags, startId);
}

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


private void setUp(JabberSmackAPI c) throws XMPPException, IOException {
    // declare variables
    c = new JabberSmackAPI();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String msg = "hi how r u!";

    // Enter your login information here
    c.login(chat_id, GlobalDeclaration.paswword);

    System.out.println("-----");

    String talkTo = "username";


}

public class JabberSmackAPI implements MessageListener, ChatManagerListener {

    public void login(String userName, String password) throws XMPPException {
        ConnectionConfiguration config = new ConnectionConfiguration("Host", 5222);
        connection = new XMPPConnection(config);

        connection.connect();

        PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
        connection.addPacketListener(packetListener, filter);


        connection.login(userName, password);

    }

}

private PacketListener packetListener = new PacketListener() {

    public void processPacket(Packet packet) {
        // TODO Auto-generated method stub
        System.out.println("In the process packet");
        System.out.println(packet.toXML());


        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
        getBaseContext().sendBroadcast(broadcastIntent);
        System.out.println("---final packrt result-- " + packectResult.trim());
    }
};

}

You can add alarm to fire every X time and this alarm can fire the service.

Solution 1: Alarm -- Call --> BroadcastReceiver -- Fire (start) --> your service.

Solution 2: Any system BroadcastReceiver (for example battery level change ) --> your service.

----- Update -------

public class BaseNotificationManager extends BroadcastReceiver {


public static final String BaseAction = "Com.TST.BaseAction";
public static final String FireService = "Com.TST.FireNotificationAction";


private  static  final long timeFrame =  1000*60*5;  // 5 mints

public BaseNotificationManager() {
}

@Override
public void onReceive(Context context, Intent intent) {

    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
        /// add base alarm manager
        startBaseAlarmManager(context);

    }else  if (BaseAction.equals(intent.getAction())){
       //  StartYourService();
    } 
}       public  static  void startBaseAlarmManager (Context context){


    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, BaseNotificationManager.class);
    intent.setAction(BaseAction);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            5000,  timeFrame, alarmIntent);

}}

Manifest

<receiver
            android:name=".BaseNotificationManager"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

Basically service is running in your background even though your app is killed.

Just call the service like,

 Intent chatService = new Intent(MainActivity.this,ChatService.class);
 startService(chatService);

You should startService and bindService If you only use bindService, it will be killed once you leave the class. StartService will keep your service alive.
As follow:

Intent intentService = new Intent(MainActivity.this, MyService.class);
startService(intentService);
bindService(new Intent(MainActivity.this, MyService.class),MainActivity.this, BIND_AUTO_CREATE);

Try to add startForeground in onStartCommand, it will raise the priority of your service. But it should come along with a notification exist.

startForeground(int id, Notification notification)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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