应用程序关闭后,后台服务即停止

时间:2017-10-04 16:24:27

标签: android service background-service

我正在创建一个消息传递应用程序,我需要一个服务来接收消息,即使应用程序关闭或打开,我有一个接收短信的广播接收器,我创建了一个服务类,并在我的mainActivity中启动

Intent mIntent=new Intent(this,BackgroundService.class);
startService(mIntent);

在清单中,我将服务添加为

 <service android:name=".BackgroundService"
            android:enabled="true"/>

broadcastReceiver类

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


    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {

        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) 
sms[i]);

            smsBody = smsMessage.getMessageBody().toString();
            address = smsMessage.getOriginatingAddress();


            smsMessageStr += "SMS FROM :" + address + "\n";
            smsMessageStr += "Message :" + smsBody + "\n";
        }
            Toast.makeText(context, smsMessageStr, 
Toast.LENGTH_LONG).show();

backgroundService.java

public class BackgroundService extends Service{

private SmsBroadcastReceiver mSmsBroadcastReceiver;
private IntentFilter mIntentFilter;
private static final int NOTIFICATION_ID = 999;


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

    mSmsBroadcastReceiver=new SmsBroadcastReceiver();
    mIntentFilter=new IntentFilter();
    mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    mIntentFilter.setPriority(999);
    registerReceiver(mSmsBroadcastReceiver,mIntentFilter);

    return START_STICKY;
}

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

我还尝试过前台服务

 Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("TutorialsFace Music Player")
            .setTicker("TutorialsFace Music Player")
            .setContentText("My song")
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();
        startForeground(NOTIFICATION_ID,
            notification);

但是一旦我从最近的应用程序关闭我的应用程序,服务也会停止 当我重新启动我的应用程序时,服务就开始了

即使应用关闭,我怎样才能让我的服务长寿。因为我的应用程序是基于SMS的,所以没有服务我不能收到我的应用程序关闭时的消息, 任何帮助将不胜感激, 提前致谢。

1 个答案:

答案 0 :(得分:0)

是的,该服务与应用程序在同一个线程中工作,您可以覆盖方法onDestroy以使用自己的线程再次启动服务。

@Override
public void onDestroy() {
    super.onDestroy();
    getApplicationContext().startService(new Intent(getApplicationContext(), BackgroundService.class));
}
相关问题