每次手机重启时我的服务都会丢失

时间:2015-09-05 08:06:57

标签: android service

我正在提供服务 到目前为止,它的表现非常好, 但每次手机重启时,服务都会丢失,

如何在每次手机关闭时重新启动服务,然后重新开启,(如果电池电量耗尽,或者用户重新启动)

有一种简单的方法吗?

这是我的服务>

package com.greenroad.candidate.mywallpaperchanger;

import android.app.Service;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by pitsponet on 31/08/2015.
 */
public class myService extends Service {
    int oneSecond = 1000;
    int oneMinute = oneSecond*60;
    int oneHour = oneMinute*60;
    int pictureNumberToChoos = 0;
    boolean isTimerRunning = false;
    int timerDeley = oneHour;

private Timer timer;
private TimerTask timerTask = new TimerTask() {

    @Override
    public void run() {
       //this timer will run again in 10 seconds
        Log.d("MyLog", "timer entered ");

        //shows a toast saying timer has entered
        Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "timer listener Entered", Toast.LENGTH_LONG).show();
            }
        });


        //takes picture modifier and updates it to +1 then stores it at var >  pictureModifireInt

        // Access the default SharedPreferences
        SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();

        //open a boolean to tell if the service is activated for the first time it will say false
        Integer pictureModifireInt = pref.getInt("pictureModifire", 0);


        pictureModifireInt++;


        /////holds a list with all the images
        int displayPicture = R.drawable.captain;

        ArrayList<Integer> pictureNames = new ArrayList<>();
        pictureNames.add(R.drawable.captain);
        pictureNames.add(R.drawable.flash);
        pictureNames.add(R.drawable.superman);
        pictureNames.add(R.drawable.thor);
        pictureNames.add(R.drawable.wonder);
        pictureNames.add(R.drawable.a);
        pictureNames.add(R.drawable.b);
        pictureNames.add(R.drawable.c);
        pictureNames.add(R.drawable.d);
        pictureNames.add(R.drawable.e);
        pictureNames.add(R.drawable.f);
        pictureNames.add(R.drawable.g);
        pictureNames.add(R.drawable.h);
        pictureNames.add(R.drawable.i);
        pictureNames.add(R.drawable.j);
        pictureNames.add(R.drawable.k);
        pictureNames.add(R.drawable.l);
        pictureNames.add(R.drawable.m);
        pictureNames.add(R.drawable.n);
        pictureNames.add(R.drawable.o);


        //logs the stored prefrence and select the correct image at place > picture modifire
        Log.d("myLog", "storedPreference: " + pictureModifireInt);
        displayPicture = pictureNames.get(pictureModifireInt-1);

        if(pictureModifireInt > 19){
            // Edit the saved preferences
            Log.d("myLog", "putting in pictureModifire : : " + 0);
            editor.putInt("pictureModifire", 0);  // getting String
            editor.commit();

        } else {
            Log.d("myLog", "putting in pictureModifire : : " + pictureModifireInt);
            editor.putInt("pictureModifire", pictureModifireInt);  // getting String
            editor.commit();
        }



        ///////////////////////////start of wallpaper implemintation
        WindowManager wm= (WindowManager) getSystemService(MainActivity.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();

        Bitmap bmap2 = BitmapFactory.decodeResource(getResources(), displayPicture);
        Bitmap bitmap = Bitmap.createScaledBitmap(bmap2, width, height, true);

        WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
        try {
            wallpaperManager.setBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }


        //////////////////////////end of wallpaper implementation
        mainHandler = new Handler(getApplicationContext().getMainLooper());
        final Integer finalPictureModifireInt = pictureModifireInt-1;

        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "wallpaper changed to : "+ finalPictureModifireInt+" and started a new timer", Toast.LENGTH_LONG).show();
            }
        });


    }
};



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

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

    Toast.makeText(getApplicationContext(), "a new service created",
            Toast.LENGTH_LONG).show();
}

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

    Log.d("MyLog", "a new service started");

    final Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
    mainHandler.post(new Runnable() {
        @Override
        public void run() {

            Toast.makeText(getApplicationContext(), "serviceStarterd", Toast.LENGTH_LONG).show();

            // Access the default SharedPreferences
            SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();

            //open a boolean to tell if the service is activated for the first time it will say false
            boolean serviceStateOn = pref.getBoolean("isServiceActivated", false);

            if(serviceStateOn == false){
                // Edit the saved preferences
                Toast.makeText(getApplicationContext(), "a New Timer Started with Delay: "+timerDeley, Toast.LENGTH_LONG).show();

                editor.putBoolean("isServiceActivated", true);  // getting String
                editor.commit();

                timer = new Timer();
                timer.scheduleAtFixedRate(timerTask, timerDeley, timerDeley);

            } else {
                Log.d ("myLog", "Service is on so do nothing");

            }



        }
    });

    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    Toast.makeText(getApplicationContext(), "service stoped",
            Toast.LENGTH_LONG).show();
    }
}

这是我的清单&gt;

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.greenroad.candidate.mywallpaperchanger" >

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

<service
    android:name=".myService"
    android:exported="false"
    />
</application>

</manifest>
感谢所有人在高级! &#34; _ 如果没有这个网站,我不会知道如何生活...

2 个答案:

答案 0 :(得分:0)

你需要制作一个能听取意图的接收器。完成。

然后在接收()中,您可以开始服务。

答案 1 :(得分:0)

您需要添加Receiver Class。

  1. 在AndroidManifest.xml文件中添加以下权限。
  2. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    1. 在AndroidManifest.xml中的Application Tag中添加以下语句

      <receiver android:name=".YourBroadcastReceiver">  
      <intent-filter>  
          <action android:name="android.intent.action.BOOT_COMPLETED" />  
      </intent-filter></receiver>
      
    2. YourBroadcastReceiver.java

    3. package com.test;

      public class MyBroadcastReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              Intent startServiceIntent = new Intent(context, MyService.class);
              context.startService(startServiceIntent);
          }
      }