MyService.class
public class MyService extends Service { public MyService() { } // 創建一個服務 @Override public void onCreate() { super.onCreate(); } // 服務啟動 @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("MyServer", "服務啟動了"); Timer timer = new Timer(); int n = 5 * 60 * 10000; timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); // TODO: 2019/11/7 AlertDialog.Builder builder=new AlertDialog.Builder(MyApp.getContext()); builder.setTitle("提示"); builder.setMessage("已經過去五分鍾了\n且行器珍惜"); builder.setNegativeButton("明白了",null); Dialog dialog=builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); Looper.loop(); } }).start(); Log.i("MyServer","五分鍾了"); } }, 10000, n); return super.onStartCommand(intent, flags, startId); } // 服務銷毀 @Override public void onDestroy() { stopSelf(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return new MyBinder(); } class MyBinder extends Binder { /** * 獲取Service的方法 * @return 返回PlayerService */ public MyService getService() { return MyService.this; } } }
注意 Looper.prepare()和 Looper.loop()這兩行,少了它們會報Can't create handler inside thread that has not called Looper.prepare()這個錯誤
在AndroidManifest中
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><!--這行代碼必須存在,否則點擊不了系統設置中的按鈕--> <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
不過服務一般在創建的時候它就會自己幫我們添加了
<service android:name=".MyService" android:enabled="true" android:exported="true"></service>
在Activity中綁定服務
public class MainActivity extends AppCompatActivity { public Intent intent; ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 建立連接 // 獲取服務操作對象 MyService.MyBinder binder = (MyService.MyBinder) service; binder.getService();//獲取到Service } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(this, MyService.class); startService(intent);//啟動服務 } @Override protected void onDestroy() { super.onDestroy(); // stopService(intent); // 程序銷毀時,退出服務 } }