Android服务即将关闭

时间:2016-12-22 13:42:01

标签: android

我正在创建一个自动壁纸更改应用程序但我遇到的问题是,当我从任务管理器/最近的应用程序关闭应用程序时,该服务正在关闭。这是我的服务代码

public class WallpaperChange extends Service implements Runnable {

    private int WallpaperId[]={R.drawable.wallpaper1,R.drawable.wallpaper2};
    //to store user selected time
    private int time;

    //declare a flag to check which image to display next
    private int FLAG=0;

    private Thread t;

    //declare two Bitmap objects to store the wallpaper images

    Bitmap bitmap1,bitmap2;

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

    @Override
    public int onStartCommand(Intent intent, int flag, int startId) {
        super.onStartCommand(intent, flag, startId);
        Toast.makeText(this,"New Time has been set",Toast.LENGTH_SHORT).show();
        Bundle bundle=intent.getExtras();

        time=bundle.getInt("time");

        //initialize the bitmap objects with the wallpaper images
        bitmap1= BitmapFactory.decodeResource(getResources(),WallpaperId[0]);
        bitmap2=BitmapFactory.decodeResource(getResources(),WallpaperId[1]);

        t=new Thread(WallpaperChange.this);
        t.start();
    //i tried Service.START_STICKY in place of 0
        return 0;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service being destroyed",Toast.LENGTH_SHORT).show();
        System.exit(0);
    }

    @Override
    public void run() {
        try
        {
            while(true)
            {
                if(FLAG==0) {
                    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());

                    myWallpaperManager.setBitmap(bitmap1);
                    FLAG++;
                }
                else
                {
                    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
                    myWallpaperManager.setBitmap(bitmap2);
                    FLAG--;
                }

                Thread.sleep(1000*time);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

我不想使用前景。没有前景是不可能的?

0 个答案:

没有答案