Answer the question
In order to leave comments, you need to log in
If I close the application, the service stops working, what should I do?
Made a test application on android. The bottom line is that the service notifies the "Notification" person when the application is closed.
When the device is turned on, the service is started using the "BroadcastReceiver", the application itself is closed and notifications work, with a time interval. We clicked on the notification and the application started, but after we close it (remove it from the list of running applications), notifications stop coming.
When starting the device, if you go to
settings->apps->activethen my application
Processes: 1, Services: 1after we launch the application or go to it through a notification and close the application (remove it from the list of running applications), the result is this:
Processes: 0, Services: 1
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);
}
}
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", "Запущен");
}
}
}
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());
}
}
}
}
}
<?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>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question