在开机或重启设备时启动Android服务

时间:2018-03-06 19:05:19

标签: java android service broadcast boot

我是android的初学者。所以,我需要你的帮助,我创建了一个Android服务,我想在设备启动时重新启动该服务,或者仅在我的服务被激活的情况下重新启动。 如果我的服务被停用,则不应该在启动或重启设备的设备上启动它。 请帮忙 感谢

2 个答案:

答案 0 :(得分:0)

要重新启动您的服务,您可以使用操作android.intent.action.BOOT_COMPLETED创建一个BrodcastReciever,然后在其中启动您的服务。如果服务在关闭时运行,您可以使用SharedPreferences进行保存。

答案 1 :(得分:0)

首先,您需要一种方法来指示服务是否已激活。在这种情况下,我使用SharedPreference,即使在应用关闭,设备重新启动等后也会持久存储public void setServiceActivated(boolean activated) { SharedPreferences sharedPreferences = context.getSharedPreferences("servicePrefs", Context.MODE_PRIVATE); SharedPreferences.Editor prefEditor = sharedPreferences.edit(); prefEditor.putBoolean("serviceActivated", activated); prefEditor.apply(); } 。您可以这样做:

BroadcastReceiver

然后,创建一个public class AutoStart extends BroadcastReceiver { // Method is called after device bootup is complete public void onReceive(final Context context, Intent arg1) { SharedPreferences sharedPreferences = context.getSharedPreferences("servicePrefs", Context.MODE_PRIVATE); boolean serviceActivated = sharedPreferences.getBoolean("serviceActivated", false); if (serviceActivated) { // Start service here } } } ,它将在设备启动过程完成时运行,如果激活它将启动您的服务:

BroadcastReceiver

最后,在清单中注册<application android:allowBackup="true" android:largeHeap="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <!-- Launches your service on device boot-up --> <receiver android:name=".AutoStart"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application>

import java.awt.*;
import java.util.*;

public class BarGraph {
    private int width;
    private int height;
    private ArrayList<Double> variables; //for storing data for bar graph
    private ArrayList<String> labels; // for storing names of x, y axes

public BarGraph(int aWidth, int aHeight, ArrayList<String> labels, ArrayList<Double> variables) {
    this.width = aWidth;
    this.height = aHeight;
    this.variables = variables;
    this.labels = labels;

}

public void add(double value, String X) {
    variables.add(value);
    labels.add(X);
}

public void draw(Graphics2D g2) {
    int i = 0;
    double max = 0;

    for (Double wrapper : variables)
        if (max < wrapper)
            max = wrapper;

    int xwidth = width - 1;
    int yheight = height - 1;

    int xleft = 0;

    for (i = 0; i < variables.size(); i++) {
        int xright = width * (i + 1) / variables.size();
        int barWidth = xwidth / variables.size();
        int barHeight = (int) Math.round(yheight * variables.get(i) / max);

        Rectangle bar =
                new Rectangle(xleft, yheight - barHeight,
                        barWidth, barHeight);
        g2.draw(bar);
        g2.setColor(Color.RED);

        xleft = xright;
    }

   }
}