在这个例子中,首先我开始活动课程 在我调用startservice(),我从服务类的oncreate方法得到“in on create”的吐司 在服务类中,我做了这个编码
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(getApplicationContext(), "in on create", Toast.LENGTH_SHORT).show();
}
public void onStart(Intent arg0, int startId) {
// TODO Auto-generated method stub
super.onStart(arg0, startId);
}
public void broadcastIntent(View view)
{
Intent intent = new Intent();
intent.setAction("android.intent.action.PHONE_STATE");
sendBroadcast(intent);
}
在广播接收器类我做了这个
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Toast.makeText(context,"Phone is Ringing", Toast.LENGTH_LONG).show();
Intent i=new Intent(context,MainActivity.class);
i.putExtra("state", state);
context.startActivity(i);
}
}
在清单文件中我做了......
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name="Start">
</receiver>
<service
android:name="Run"></service>
答案 0 :(得分:1)
在清单中声明接收器......
<receiver
android:name=".Start"
android:priority="999" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
此处android:name=".Start"
代表BroadcastReceiver
的班级名称。此处Start
是BroadcastReceiver
的类名,其包名称等于Application
的包名称(您的应用的包名称),并且您不允许手动发送android.intent.action.PHONE_STATE
广播
来自评论,这可能会对您有所帮助。
toggleButton
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
buttonView
.getContext()
.getSharedPreferences("app_preference",
Context.MODE_PRIVATE).edit()
.putBoolean("IS_RECEIVER_ENABLED", isChecked)
.commit();
}
});
并在onReceive()
@Override
public void onReceive(Context context, Intent intent) {
boolean isEnabled = context.getSharedPreferences("app_preference",
Context.MODE_PRIVATE).getBoolean("IS_RECEIVER_ENABLED",
false);
if (isEnabled) {
// Show Toast here.
}
}