Я хочу показывать изображение в формате GIF на экране, даже когда приложение закрыто

Щелчком мыши вы реализуете две вещи:

  • Звук играет
  • Изображение в формате GIF показывает
    .

Я пытаюсь показать GIF на экране, даже когда закрываю приложение, в котором я использую службы, но поскольку звук продолжает воспроизводиться, пока появляется изображение GIF, я не могу найти решение.

TheService.java (КОД)

package gallery.suitapps.catwalking;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import pl.droidsonroids.gif.GifImageView;

public class TheService extends Service  {

    final class MyThreadClass implements Runnable{
        int service_id;
        MyThreadClass(int service_id){
            this.service_id=service_id;
        }

        @Override
        public void run() {

        }
    }

    SoundPool soundPool = null;
    private int[] f10685s;


    MainActivity main = new MainActivity();

    public MediaPlayer player;
    Context context;

    @Override
    public void onCreate() {
        super.onCreate();
    }

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

        Toast.makeText(this,"Service Starts" , Toast.LENGTH_SHORT).show();
        player = MediaPlayer.create(this,R.raw.sound2);
        player.setLooping(true);
        player.start();

        MainActivity.imageView.setImageResource(R.drawable.cat_gif);

        return START_STICKY;

    }

    @Override
    public void onDestroy() {
        Toast.makeText(this,"Service Stops" , Toast.LENGTH_SHORT).show();
        player.stop();
        MainActivity.imageView.setImageResource(R.drawable.ic_launcher_background);
    }

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

}

MainActivity.java (КОД)

package gallery.suitapps.catwalking;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import pl.droidsonroids.gif.GifImageView;

public class MainActivity extends AppCompatActivity {

    public static GifImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.catgif);
    }

    public void startService (View view){

        Intent intent = new Intent(this,TheService.class);
        startService(intent);

       // imageView.setImageResource(R.drawable.cat_gif);

    }

    public void stopService (View view){

        Intent intent = new Intent(this,TheService.class);
        stopService(intent);

    }


}

activity_main.xml

 <?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">

    <Button
        android:id = "@+id/startService"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginBottom = "8dp"
        android:layout_marginEnd = "8dp"
        android:layout_marginLeft = "8dp"
        android:layout_marginRight = "8dp"
        android:layout_marginStart = "8dp"
        android:layout_marginTop = "8dp"
        android:text = "Start Service"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.501"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent"
        app:layout_constraintVertical_bias = "0.134"
        android:onClick = "startService"/>

    <Button
        android:id = "@+id/stopService"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginBottom = "8dp"
        android:layout_marginEnd = "8dp"
        android:layout_marginLeft = "8dp"
        android:layout_marginRight = "8dp"
        android:layout_marginStart = "8dp"
        android:layout_marginTop = "8dp"
        android:text = "Stop Service"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.502"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent"
        app:layout_constraintVertical_bias = "0.362"
        android:onClick = "stopService"/>

    <pl.droidsonroids.gif.GifImageView
        android:id = "@+id/catgif"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:src = "@drawable/ic_launcher_background"
        android:background = "@android:color/holo_blue_dark"
        />

</android.support.constraint.ConstraintLayout>

проверьте мой ответ, дайте мне знать, работает он или нет

Quick learner 18.09.2018 09:43

Да, это работает, но не совсем то, что я хочу, он перемещает весь экран приложения на экране мобильного телефона, в то время как я просто хочу, чтобы GIF плавал по экрану.

Shah Jehan 18.09.2018 12:34

хорошо, какая часть экрана вы хотите это показать?

Quick learner 18.09.2018 13:05

проверьте мое обновление в моем ответе :)

Quick learner 18.09.2018 13:07
1
4
99
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

According to your requirement you need to implement system window alert in service class to show image in background when the app is closed

Это решение для ваших требований.

В manifest добавьте это

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

Затем в вашем лаунчере activity или любой базовой активности добавьте эти разрешения

 private static final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;

В onCreate() добавьте это

if (SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
            //finish();
        }

Обработка разрешения запроса

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CODE_DRAW_OVER_OTHER_APP_PERMISSION) {
            if (SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
            } else {
               // do stuff here 
            }
        }
    }

и сделайте это в классе service, проверьте ссылку ниже и выполните свои действия соответственно

   https://medium.com/@kevalpatel2106/create-chat-heads-like-facebook-messenger-32f7f1a62064

где image_layout. xml - это

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">

    <pl.droidsonroids.gif.GifImageView
        android:id = "@+id/catgif"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:src = "@drawable/ic_launcher_background"
        android:background = "@android:color/holo_blue_dark"
        />

</android.support.constraint.ConstraintLayout>

Update:- You can make changed in image_layout file to show your GIF any size and gravity in the screen You can make changes with

android:layout_width = "any_size"
    android:layout_height = "any_size"

Другие вопросы по теме