贵有恒,何必三更起、五更眠、最无益,只怕一日曝、十日寒。这篇文章主要讲述Android 在Service中弹出对话框相关的知识,希望能为你提供帮助。
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("已经过去五分钟了 且行器珍惜"); 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); //程序销毁时,退出服务 }}
【Android 在Service中弹出对话框】
推荐阅读
- AppBarLayout折叠时候的阴影
- Java Applet基础——输出HelloWorld
- 把app(apk和ipa文件)安装包放在服务器上供用户下方法
- DApp是什么,DApp是必然趋势
- Android在Service中弹出对话框二
- H5页面测试app测试
- 前端随心记---------call,bind,apply
- SEAndroid
- Android(View上更改鼠标样式及坐标监听)