首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

【android】利用service监听回电或来信息

2012-07-25 
【android】利用service监听来电或来信息写这个东西只是为了练手,拍砖随意。反正自己也是菜鸟。微信/QQ在退出

【android】利用service监听来电或来信息
写这个东西只是为了练手,拍砖随意。反正自己也是菜鸟。
微信/QQ在退出主界面之后还是会一直监听消息。如何实现呢?
一下做的测试,监听为用户的新信息。
首先:建立主程序界面

    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="start" />    <Button        android:id="@+id/button2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="stop" />

两个button。

其次:绑定监听事件
start.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubSystem.out.println("ooooo");startService(new Intent("com.duduli.li.My"));}});                stop.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubstopService(new Intent("com.duduli.li.My"));}});

这里的intent需要在manifest中进行注册。

        <service android:name=".Myservice">            <intent-filter>                <action android:name="com.duduli.li.My"/>                <category android:name="android.intent.category.DEFAULT"/>            </intent-filter>        </service>

service类方法:
public class Myservice extends Service{@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubSystem.out.println("on bind");return null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();System.out.println("on create");}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);System.out.println("on start");new Test();}}


onstart方法中有个Test的实力,这个实力就是一个BroadcastReceiver用来监听来电或来信息。
public class Test extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubif(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){                        System.out.println(System.currentTimeMillis());System.out.println("broadcast begin");}}}




这个broadcastreceiver也需要在manifest中进行注册/
        <receiver android:name=".Test">            <intent-filter>                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>            </intent-filter>        </receiver>


action对应的就是收到新信息。











热点排行