Попытка запустить приложение в фоновом режиме (свернуто / экран заблокирован / удалено из запущенного приложения) - PullRequest
0 голосов
/ 17 июня 2020

Я пишу приложение android, которое будет вызывать SMS при обнаружении пропущенного вызова. Пока я могу обнаружить пропущенный вызов и отправить SMS вызывающему абоненту.

Если я запустил свое приложение, (включил ПЕРЕКЛЮЧАТЕЛЬ (например, умный переключатель), который проверяет наличие звонящего вызова и обнаруживает пропущенный вызов ), а затем кто-то звонит, и если это пропущенный вызов, SMS отправляется правильно. Если я сворачиваю свое приложение (не блокируйте телефон) и открываю приложение Instagram / Другое, тогда также SMS отправляется вызывающему абоненту.

НО,

, когда мое приложение (умный переключатель для включения этой функции горит), но я закрываю приложение, SMS не отправляется. когда мое приложение свернуто (экран заблокирован), сообщение не запускается. (Умный переключатель включен), когда мое приложение открыто (экран заблокирован), сообщение не запускается. (Умный переключатель включен)

Я новичок в android. Пожалуйста, помогите мне, я хочу, чтобы мое приложение работало, если мой SMART SWITCH включен, мое приложение будет продолжать отслеживать пропущенный вызов и отправлять SMS вызывающему абоненту независимо от приложения в фоновом режиме, заблокированного экрана или нет, пока мой интеллектуальный переключатель ВКЛЮЧЕНО.

Ответы [ 2 ]

0 голосов
/ 23 июня 2020

Я попытался запустить службу, и она сработала, для работы фона нам нужен передний план.

public class myservices extends Service

{@Override publi c int onStartCommand (Intent intent, int flags, int startId ) {Intent notificationIntent = new Intent (this, MainActivity.class); // Чтобы открыть MainActivity onClick PendingIntent pendingIntent = PendingIntent.getActivity (this, 0, notificationIntent, 0);

    Intent busy = new Intent(this, InterceptCall.class);
    Intent driving = new Intent(this, InterceptCall.class);
    Intent meeting = new Intent(this, InterceptCall.class);
    busy.putExtra("mode","busy");
    driving.putExtra("mode", "driving");
    meeting.putExtra("mode", "meeting");
    PendingIntent busyIntent = PendingIntent.getBroadcast(this, 1, busy, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar
    PendingIntent drivingIntent = PendingIntent.getBroadcast(this, 2, driving, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar
    PendingIntent meetingIntent = PendingIntent.getBroadcast(this, 3, meeting, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Smart Mode is on ")
            .setContentText("Drag down to display modes.")
            .setContentIntent(pendingIntent)
            .setColor(Color.MAGENTA)
            .setSmallIcon(R.drawable.pingedlogo)
            .addAction(R.mipmap.ic_launcher, "Busy", busyIntent)
            .addAction(R.mipmap.ic_launcher, "Driving", drivingIntent)
            .addAction(R.mipmap.ic_launcher, "Meeting", meetingIntent)
            .build();

    startForeground(1, notification);
    return START_NOT_STICKY;
}
0 голосов
/ 17 июня 2020

Первое, у вас должно быть разрешение на задачу

<uses-permission android:name="android.permission.WAKE_LOCK" />

Пример кода

 Thread(Runnable {
        // a potentially time consuming task
        val bitmap = processBitMap("image.png")
        imageView.post {
            imageView.setImageBitmap(bitmap)
        }
    }).start()

Также вам нужно

Рекомендую поискать следующий страница

https://developer.android.com/guide/components/processes-and-threads

Обзор услуг

Вот как я это решил.

publi c класс myservices расширяет службу {@Override publi c int onStartCommand (намерение намерения, int флаги, int startId) {Intent notificationIntent = new Intent (this, MainActivity.class); // Чтобы открыть MainActivity onClick PendingIntent pendingIntent = PendingIntent.getActivity (this, 0, notificationIntent, 0);

    Intent busy = new Intent(this, InterceptCall.class);
    Intent driving = new Intent(this, InterceptCall.class);
    Intent meeting = new Intent(this, InterceptCall.class);
    busy.putExtra("mode","busy");
    driving.putExtra("mode", "driving");
    meeting.putExtra("mode", "meeting");
    PendingIntent busyIntent = PendingIntent.getBroadcast(this, 1, busy, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar
    PendingIntent drivingIntent = PendingIntent.getBroadcast(this, 2, driving, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar
    PendingIntent meetingIntent = PendingIntent.getBroadcast(this, 3, meeting, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Smart Mode is on ")
            .setContentText("Drag down to display modes.")
            .setContentIntent(pendingIntent)
            .setColor(Color.MAGENTA)
            .setSmallIcon(R.drawable.pingedlogo)
            .addAction(R.mipmap.ic_launcher, "Busy", busyIntent)
            .addAction(R.mipmap.ic_launcher, "Driving", drivingIntent)
            .addAction(R.mipmap.ic_launcher, "Meeting", meetingIntent)
            .build();

    startForeground(1, notification);
    return START_NOT_STICKY;
}
...