1. 程式人生 > >關於實現重啟 App 的兩種思路

關於實現重啟 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);
    }

參考文章