【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" />
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"));}});
<service android:name=".Myservice"> <intent-filter> <action android:name="com.duduli.li.My"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </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();}}
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");}}}
<receiver android:name=".Test"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver>