今天做了一个小demo。主要是想回顾一下BroadcastReceiver的手动注册的方法,同时也温习一下service 布局文件main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ipdial.MainActivity" >
<Switch
android:id="@+id/switch1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="服务开关"
android:textOff="服务已关闭"
android:textOn="服务已开启" />
</RelativeLayout>
MainActivity.java
package com.example.ipdial;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
public class MainActivity extends Activity {
private Switch switch1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
switch1 = (Switch) findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
startService(new Intent(MainActivity.this, MyService.class));
Toast.makeText(MainActivity.this, "startService",
Toast.LENGTH_SHORT).show();
} else {
stopService(new Intent(MainActivity.this, MyService.class));
Toast.makeText(MainActivity.this, "stopService",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
对应的service代码:
package com.example.ipdial;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
private MyReceiver myReceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
registerReceiver(myReceiver, filter);
}
@Override
public void onDestroy() {
unregisterReceiver(myReceiver);
}
public static class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "MyReceiver", Toast.LENGTH_SHORT).show();
//监听去电
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
if(number.equals("12345")){
setResultData("12345" + number);
}
}
}
}
}
BroadcastReceiver 是手动注册的,所以清单文件不用再注册,但是service需要注册、
<service android:name="MyService"></service>
当然还需要权限:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
PS:avd在打电话的时候会断开连接,DDMS下会是一片空白
键入如下代码即可: