我创建了一个具有两个按钮的Android应用程序,分别设置墙纸和重置墙纸。在设置的WallPaper上,我在drawable文件夹中有图像,这些图像被设置为墙纸,并在一定间隔内使用WallpaperManger和服务来实现。一切正常。在单击“重置壁纸”后,我需要重置为手机的默认壁纸。在按钮上,单击“我叫stopService
”以停止设置墙纸的服务。它调用destroy方法并重置墙纸,但过一会儿服务触发设置墙纸。请指导我解决此问题。
MainActivity
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setWallpaperBtn = (Button)findViewById(R.id.setWallpaper);
resetWallpaperBtn = (Button)findViewById(R.id.resetWallpaper);
//on click of set wallpaper button
setWallpaperBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,WallPaperService.class);
startService(intent);
}
});
WallPaperService extends Service
@Override
public void onCreate() {
super.onCreate();
myTimer=new Timer();
myWallpaperManager = WallpaperManager.getInstance(WallPaperService.this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
myTimertask = new TimerTask() {
// Bitmap bitmap =BitmapFactory.decodeResource(getResources(),R.drawable.two);
@Override
public void run() {
if (prev == 1) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeResource(getResources(),R.drawable.two,options);
options.inSampleSize=2;
options.inJustDecodeBounds=false;
bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.two,options);
prev = 2;
}continues for other images...
try {
myWallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
};
myTimer.schedule(myTimertask,interval,startInterval);
return super.onStartCommand(intent,flags,startId);
}
@Override
public void onDestroy(){
try {
myWallpaperManager.clear();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this,"invoke destroy",Toast.LENGTH_LONG).show();
}