關於實現重啓 App 的兩種思路

思路

  1. 方案1:創建一個服務類,在該類中創建一個定時器,每隔一段時間觸發該定時器,並獲取到系統時間與指定重啓的時間做匹配,匹配成功的話,發送一條廣播,在廣播中處理重啓 App 邏輯。
  2. 方案2:監聽系統時間廣播,Intent.ACTION_TIME_TICK 含義:系統每分鐘會發出該廣播,通過監聽該廣播,滿足對應條件的時候重啓 App。

方案1實現

自定義 ReStartAppService 類

package com.example.a002034.restartapp.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


/**
 * service.
 */
public class ReStartAppService extends Service {
    public static final String RESTART_ACTION = "com.xzy.test.RESTART_APP";

    private IBinder mBinder = new Binder();
    private Timer mTimer;
    private TimerTask mTimerTask;
    private Intent intent = new Intent(RESTART_ACTION);

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

    @Override
    public void onCreate() {
        // 演示代碼,所以只用原始寫法,也可以使用 RxJava
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("HH");
                        String dateStr = sdf.format(new Date());
                        // 凌晨 2 點重啓
                        if (dateStr.equals("02")) {
                            sendBroadcast(intent);//發送廣播
                        }

                    }
                }).start();
            }
        };
        // 單位是毫秒,建議這裏作延遲一小時處理,仔細思考下你就懂了
        mTimer.schedule(mTimerTask, 3600 * 1000, 3600 * 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();
        mTimerTask.cancel();
        if (mTimer != null) {
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask = null;
        }
    }
}

在 xml 中添加 service 標籤

  <service android:name=".service.ReStartAppService"/>

Activity 中的寫法

package com.example.a002034.restartapp;

import static com.example.a002034.restartapp.service.ReStartAppService.RESTART_ACTION;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.example.a002034.restartapp.service.ReStartAppService;

import java.util.Objects;

public class MainActivity extends Activity {
    private ServiceConn mServiceConn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mServiceConn = new ServiceConn();
    }


    @Override
    protected void onResume() {
        super.onResume();
        startMyService();//開啓服務
        IntentFilter filter = new IntentFilter();
        filter.addAction(RESTART_ACTION);
        registerReceiver(reStartReceiver, filter);
    }

    /**
     * start service method.
     */
    private void startMyService() {
        Intent intent = new Intent(getApplicationContext(), ReStartAppService.class);
        bindService(intent, mServiceConn, BIND_AUTO_CREATE);
    }


    /**
     * defined ServiceConnection class.
     */
    private class ServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("--------", "------開啓重啓app服務成功---");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }


    /**
     * 廣播接收.
     */
    private BroadcastReceiver reStartReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Objects.equals(action, RESTART_ACTION)) {
                // restart app
                restartApp();
            }
        }
    };


    /**
     * 重新啓動App -> 殺進程,會短暫黑屏,啓動慢
     */
    public void restartApp() {
        //啓動頁
        Intent intent = new Intent(MainActivity.this, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 重新啓動App -> 不殺進程,緩存的東西不清除,啓動快
     */
    public void restartApp2() {
        final Intent intent = getPackageManager()
                .getLaunchIntentForPackage(MainActivity.this.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // do not forget to add these codes.
        unregisterReceiver(reStartReceiver);
        unbindService(mServiceConn);
    }
}

以上代碼實現的是每隔 1 小時,去檢查系統時間是否滿足重啓條件(例子中重啓條件爲,凌晨 2 點)

方案2實現

定義廣播接受者類

package com.example.a002034.restartapp;

import static android.content.Intent.ACTION_TIME_TICK;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.Calendar;
import java.util.Objects;

/**
 * receiver.
 */
public class ReStartReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // 方案2
        if (Objects.equals(action, ACTION_TIME_TICK)) {
           // 這裏採用靜態方法獲取時間
            int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
            int minute = Calendar.getInstance().get(Calendar.MINUTE);
            Log.i("", "time: hour=" + hour + ",minute=" + minute);
            if (hour == 2 && minute == 0) {
                // restart app
//                restartApp();
            }
        }
    }
}

註冊廣播

<receiver android:name="com.example.a002034.restartapp.ReStartReceiver">
            <intent-filter>
                <action android:name="android.intent.action.TIME_TICK"/>
            </intent-filter>
        </receiver>

具體的重啓方法

 /**
     * 重新啓動App -> 殺進程,會短暫黑屏,啓動慢
     */
    public void restartApp() {
        //啓動頁
        Intent intent = new Intent(MainActivity.this, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 重新啓動App -> 不殺進程,緩存的東西不清除,啓動快
     */
    public void restartApp2() {
        final Intent intent = getPackageManager()
                .getLaunchIntentForPackage(MainActivity.this.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

參考文章

https://blog.csdn.net/wxd_beijing/article/details/70139239
https://blog.csdn.net/hb8676086/article/details/51044110

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章