你可以试试广播接收器。这是我的 BroadcastReceiver 的类和 MainActivity。在这里,我只是在应用程序处于后台时发送一条消息(来电):
主要活动:
public class MainActivity extends AppCompatActivity {
BroadcastReceiver callReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
checkPermission();
callReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
/*Do Whatever You Want When You Reciveing a Call And App is Open*/
}
};
IntentFilter callFilter = new IntentFilter("android.intent.action.PHONE_STATE");
registerReceiver(callReceiver, callFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(callReceiver);
}
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
}
}
}
这是我的 BroadcastReceiver 类:
public class IncomingCallReciver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, ".:Incoming Call:.", Toast.LENGTH_SHORT).show();
/*Do Whatever You Want When You Reciveing a Call And App is In Background*/
}
}
然后在Manifest中添加READ_PHONE_STATE
Permission,在Manifest中添加BroadcastReceiver的类,在Application Tag里面:
<receiver android:name=".IncomingCallReciver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>