【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() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("ooooo");
				startService(new Intent("com.duduli.li.My"));
			}
		});
        
        stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopService(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{
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("on bind");
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		System.out.println("on create");
		
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		System.out.println("on start");
		
		new Test();
	}


}

onstart方法中有个Test的实力,这个实力就是一个BroadcastReceiver用来监听来电或来信息。

public class Test extends BroadcastReceiver {
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(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>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值