背景
需要一个监控短信,然后转发服务器的应用
需要使用Service
android中的Service是一种后台运行的程序,如果正常的android的app,在手机进入休眠后,会被挂起,或者如果使用内存过多会被直接杀掉,这样就无法达到后台监控运行的效果了,因此需要使用Service,Service相当于开了另一个进程,可以在休眠的状态下还继续运行,因此,如果要达到需求的效果,就必须使用Service
首先,需要创建一个Service
1
2
3
4
5
6
7
8
9
10
11public class HandleMessageService extends Service { @Override public void onCreate() { //用于初始化Service } @Override public int onStartCommand(Intent intent, int flags, int startId) { //你需要进行的操作 } }
然后需要引用Service
在MainActivity中:
1
2
3Intent intent = new Intent(MainActivity.this, HandleMessageService.class); startService(intent);
这段代码可以写在你绑定的按钮中,利用按钮启动服务,当然,也可以在onCreate()中使用,看需求
需要更新UI界面
我需要将我的此次运行的操作实时的反馈给UI页面,当时,现在服务又相当于另一个进程了,就算不是另一个进程,如果开了另一个线程,android也不允许在另一个线程中更新主线程的控件内容,因此,我需要想一个另外的途径去实现这个功能。经过度娘的帮助,我发现,实现这个功能的方法有好几个,其中比较简单的就是以广播的形式进行通知,在Service中使用广播,在MainActivity中接收广播,直接上代码
创建广播的接收器
我这里这个广播的接收器是作为MainActivity的内部类创建的,原因:比较容易获取MainActivity中的控件,直接进行更新就可以了
1
2
3
4
5
6
7
8
9
10/** * @author dtw * */ class DataReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //进行更新控件 } }
注册广播
一般注册广播可以有两种方式,一种是静态注册,一种是动态注册
静态注册
1
2
3
4
5
6<receiver android:name=".MainActivity$DataReceiver"> <intent-filter> <action android:name="android.intent.action.EDIT"/> </intent-filter> </receiver>
这段xml的配置需要写在app的配置文件中,即,你配置权限的文件那里(AndroidManifest)
动态注册
1
2
3
4
5
6BroadcastReceiver broadcastReceiver = new DataReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_EDIT); registerReceiver(broadcastReceiver,intentFilter);
注意
由于我们现在使用的是内部类,因此,得进行动态注册
使用广播
1
2
3
4
5Intent intent = new Intent(); intent.setAction(Intent.ACTION_EDIT); intent.putExtra("content", content); sendBroadcast(intent);
在Service使用这段代码
特别说明
在上面广播的注册中,有一个IntentFilter的参数,他里面设置了一个值:Intent.ACTION_EDIT,这个值必须要和使用广播时的intent.setAction(Intent.ACTION_EDIT);对应上,要不然没办法接收
最后
以上就是鲤鱼康乃馨最近收集整理的关于写一个后台运行的android的思路背景需要使用Service需要更新UI界面的全部内容,更多相关写一个后台运行内容请搜索靠谱客的其他文章。
发表评论 取消回复