Если закрыть приложение, асинхронность в сервисе не работает

Ответить
RAPOS
Сообщения: 2
Зарегистрирован: 20 дек 2015, 22:54

Если закрыть приложение, асинхронность в сервисе не работает

Сообщение RAPOS » 21 дек 2015, 19:03

Сделал тестовое приложение на андроиде. Суть в том, чтобы сервис уведомлял человека "Notification" когда приложение закрыто.

При включении устройства запускается сервис с помощью "BroadcastReceiver" само же приложение закрыто и уведомления работают, с интервалом времени. Кликнкули на уведомление и запустилось приложение, но после того, как мы его закрываем (убираем из списка запущенных приложений), то уведомления перестают приходить как буд-то сервис на паузе.

При запуске устройства если зайти в

Код: Выделить всё

настройки->приложения->активные
то у моего приложения
Процессы: 1, Службы: 1
после того как мы запускаем приложение или переходим в него через уведомление и закрываем приложение (убираем из списка запущенных приложений) то результат такой:
Процессы: 0, Службы: 1
Я уже всё перепробовал, не знаю что делать, нужна помощь.

<b>MainActivity.java</b>
И использую стандартный <b>BlankActivity</b>
[syntax=java]
package ru.tagil_cs.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});

startService(new Intent(MainActivity.this, MyService.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}
[/syntax]

<b>MyResiver.java</b>
[syntax=java]
package ru.tagil_cs.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
Log.d("AutoStart", "Запущен");
}
}
}
[/syntax]

<b>MyService.java</b>
[syntax=java]
package ru.tagil_cs.test;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.concurrent.TimeUnit;

public class MyService extends Service {
private static final int NOTIFY_ID = 101;

@Override
public void onCreate()
{
Log.d("CallService", "Create");
//Toast.makeText(this, "Служба создана", Toast.LENGTH_SHORT).show();
}

@Override
public void onStart(Intent intent, int startid)
{
GetRequest();
Log.d("CallService", "Старт");
//Toast.makeText(this, "Служба запущена", Toast.LENGTH_SHORT).show();
}

public void onDestroy() {
super.onDestroy();
Log.d("CallService", "onDestroy");
}

public IBinder onBind(Intent intent) {
Log.d("CallService", "onBind");
return null;
}

public void GetRequest() {
new UserDealsTask().execute((Void) null);
}

public class UserDealsTask extends AsyncTask<Void, Void, String> {

UserDealsTask() {}

@Override
protected String doInBackground(Void... params) {
String responseJSON = "{}";
try {
Log.d("CallService", "GetRequest Спит");
TimeUnit.SECONDS.sleep(30);
Log.d("CallService", "GetRequest Старт");
GetRequest();
} catch (InterruptedException e) {
e.printStackTrace();
}
return responseJSON;
}

@Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
if(strJson != null) {
//Формирование уведомления
Context context = getApplicationContext();

Resources res = context.getResources();
Notification.Builder builder = new Notification.Builder(context);

Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.putExtra("notify", 1);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent contentIntent = PendingIntent.getActivity(context,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);

builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_icons)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_icons))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setTicker("Новый запрос на технику.") // текст в строке состояния
.setContentTitle("Объявление №" + 1) // Заголовок уведомления
.setContentText("213123123123"); // Текст уведомления

NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notificationManager.notify(NOTIFY_ID, builder.build());
} else {
notificationManager.notify(NOTIFY_ID, builder.getNotification());
}
}
}
}
}
[/syntax]

<b>AndroidManifest.xml</b>
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.tagil_cs.test">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.QUICKBOOT_POWERON" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>

<service
android:name=".MyService"
android:enabled="true"
android:exported="true"/>
<!-- Так тоже делал
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:process=":myservice"/>
-->
</application>

</manifest>[/syntax]

RAPOS
Сообщения: 2
Зарегистрирован: 20 дек 2015, 22:54

Re: Если закрыть приложение, асинхронность в сервисе не рабо

Сообщение RAPOS » 22 дек 2015, 19:19

Тему можно закрыть. Данный баг появился начиная с версии Android 4.4.2
Ножно в сервисе использовать метод onTaskRemoved(Intent rootIntent)
Он вызывается когда закрывают (не сворачивают) Приложение.
http://developer.android.com/intl/ru/re ... nt.Intent)

Ответить