关闭应用程序后,Android IntentService被杀死

时间:2019-07-18 01:06:20

标签: android

我有向服务器发送请求的android应用程序。

我的应用程序运行时,我的应用程序已成功发送请求,

但是当我关闭应用程序时,我的IntentService停止发送任何请求

我的IntentService代码:

public class ServiceNotification extends IntentService {
    public static boolean ServiceIsRun = false;
    public static int NotifiationID = MainActivity.NotificatiosFromServer;
    public String Id = MainActivity.Id;
    public String NotifiationMessage;

    public ServiceNotification() {
        super("ServiceNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        while (ServiceIsRun) {
            try { // here the function send requests to server and i print this request in server console.
                GetUserNotification(new MainPage.VolleyCallBack() {
                    @Override
                    public void onSuccess() {
                        NotifiationID++;
                    }
                });
            } catch (Exception e) {

            }

            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
            }
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }

BroadcastReceiver代码:

public class MyReceiver extends BroadcastReceiver {
    public static int id = 1;
    @Override
    public void onReceive(Context context, Intent intent) {
        // get the bundles in the message
        final Bundle bundle = intent.getExtras();
        // check the action equal to the action we fire in broadcast,
        if (intent.getAction().equalsIgnoreCase("com.example.Broadcast")) {
            id++;
            //read the data from the Intent Service
            NewNotificationMessage notfilyme = new NewNotificationMessage();
            notfilyme.notify(context, bundle.getString("msg"), bundle.getString("Image"),  bundle.getInt("Id"));
        }

    }
}

ActivityMain.java

public class MainActivity extends AppCompatActivity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
if (!ServiceNotification.ServiceIsRun) {
                                ServiceNotification.ServiceIsRun = true;
                                //register the services to run in background
                                Intent intent = new Intent(getApplicationContext(), ServiceNotification.class);
                                // start the services
                                startService(intent);
                            }
}
}

清单


<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@drawable/applicationicon"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar"
        android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>
<receiver
            android:name=".MyReceiver"
            android:priority="2147483647">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver> <!-- register the service -->
        <service
            android:name=".ServiceNotification"
            android:exported="false"
            android:enabled="true">
        </service>
    </application>

在我的应用程序关闭后,如何保持Intent Service的工作

3 个答案:

答案 0 :(得分:0)

首先您可以尝试:

    public ServiceNotification() {
        super("ServiceNotification");
        setIntentRedelivery(true); // this will restart your service after app gets killed
    }

看看这是否适合您,我认为您需要在没有电源的情况下在真实手机上进行测试。由于Android不允许长时间的任务在后台运行而不通知用户节省电量,因此您的服务很可能会在一段时间后停止,因此如果您关闭屏幕,服务会更短。

因此,替代方法是启动前台服务,如下所示:

    @Override
    protected void onHandleIntent(Intent intent) {
        String msg = intent.getStringExtra(EXTRA_MESSAGE);

        startForeground(1, getNotification());
        // do your work here
        while (ServiceIsRun) {
            // do the work and see if it completes
            // if it is completed, call: 
            // stopForegrond(true);
            // stopSelf();
            // break;
        }
   }

   // create the notification but it maybe not shown on Android 8.0+
   // because we don't create/set the notification channel
   private Notification getNotification() {
        NotificationCompat.Builder b=new NotificationCompat.Builder(this);

        b.setOngoing(true)
                .setContentTitle("title")
                .setContentText("text")
                .setSmallIcon(android.R.drawable.stat_sys_download)
                .setTicker("ticker");

        return(b.build());
    }     

答案 1 :(得分:0)

尝试在清单中的服务中添加android:stopWithTask="false",如下所示:

<service
      android:name=".ServiceNotification"
      android:exported="false"
      android:enabled="true"
      android:stopWithTask="false"> 
</service>

添加它会使您的服务继续运行,即使该应用程序已关闭/被杀死。


此外,您还需要不显示持久的通知,为此您可以使用JobIntentService

更多信息:https://developer.android.com/about/versions/oreo/background

答案 2 :(得分:0)

Android IntentService旨在处理工作线程中运行时间长但寿命短的工作。与在主线程中运行的服务不同,它保证在工作线程中运行。如果您想要的工作可以持续很长时间并且超出应用程序的寿命,那么完成该任务的一种方法是使用常规服务并创建一个新线程。以粘性启动服务,即使用户重新启动您的应用程序,它也将启动。