重启后自动运行服务

时间:2021-02-18 11:03:42

标签: android

我希望我的服务(现在的 Toast 消息)在启动后自动运行并具有以下代码:

大型活动

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

<receiver
        android:enabled="true"
        android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true" >
    </service>

启动接收器

public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

{
        /****** For Start Activity *****/

        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

        /***** For start Service  ****/
        /*
        Intent myIntent = new Intent(context, MyService.class);
        context.startService(myIntent);
         */
    }
}

}

我的服务

public class MyService extends Service {
public int counter=0;

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
        startMyOwnForeground();
    else
        startForeground(1, new Notification());
}

@RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
    String NOTIFICATION_CHANNEL_ID = "example.permanence";
    String channelName = "Background Service";
    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    Notification notification = notificationBuilder.setOngoing(true)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    startForeground(2, notification);
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    startTimer();
    return START_STICKY;
}


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

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("restartservice");
    broadcastIntent.setClass(this, Restarter.class);
    this.sendBroadcast(broadcastIntent);
}



private Timer timer;
private TimerTask timerTask;
public void startTimer() {
    timer = new Timer();
    timerTask = new TimerTask() {
        public void run() {
            Log.i("Count", "=========  "+ (counter++));

            //THIS PART RUNS EVEN AFTER APP IS KILLED
            if (counter > 10)
            {
                counter = 0;
                Log.i("Count", "runBGProcess");     //if not already running

                //Bring Toast To Foreground
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "runBGProcess", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    };
    timer.schedule(timerTask, 1000, 1000); //
}

public void stoptimertask() {
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}

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

}

主活动

public class MainActivity extends AppCompatActivity {

Intent intent;
Intent mServiceIntent;
private MyService mYourService;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //SERVICE CALL
    mYourService = new MyService();
    mServiceIntent = new Intent(this, mYourService.getClass());
    if (!isMyServiceRunning(mYourService.getClass())) {
        startService(mServiceIntent);
    }
}

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            Toast.makeText(this, "Service is Running", Toast.LENGTH_LONG).show();
            return true;
        }
    }
    Toast.makeText(this, "Service is not Running", Toast.LENGTH_LONG).show();
    return false;
}

@Override
protected void onDestroy() {
    //stopService(mServiceIntent);

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("restartservice");
    broadcastIntent.setClass(this, Restarter.class);
    this.sendBroadcast(broadcastIntent);
    super.onDestroy();
}
}
  • 当应用程序启动并且我终止该应用程序时,该服务会继续运行 - 好的
  • 当应用程序在前台并且我重新启动手机时,应用程序将出现在正在运行的应用程序菜单中(通过按方形按钮)但服务未运行 - 不正常
  • 当应用从前台被杀死时,即使服务会继续运行,在这种状态下重启手机也不会运行服务,更不用说从正在运行的应用菜单中显示应用了 - 不是

有没有办法我的 Toast“runBGProcess”(来自 MyService 类)可以在启动后在后台运行而无需先启动应用程序(它必须在后台运行/重启后隐藏服务),所以即使应用程序在运行时,它应该会在下次启动时在后台自动运行。

0 个答案:

没有答案