问题
I want to launch my application through dial pad.I am using the following code. For dial pad to launch application (in Broadcast receiver)
public class HiddenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try{
// Toast.makeText(context,"Number Dialed",1).show();
Intent serviceIntent = new Intent(context,MainActivity.class);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(serviceIntent);
}
catch(Exception e)
{
Log.d(TAG, ""+e.getMessage());
}
While pressing key through dial pad I want to launch my main activity in which I used the following
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hidden_receiver);
//Intent call here
Intent intent=getIntent();
String message = intent.getStringExtra(MainActivity.TELEPHONY_SERVICE);
//text here
But when I press my code its dialed number disappear but neither dialer pad disappear nor MainActivity launches. how can this issues be resolved?Help me out..... Thanks.
回答1:
Use the BroadcastReceiver
as follows:
public class MyOutgoingCallHandler extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Extract phone number reformatted by previous receivers
String phoneNumber = getResultData();
if (phoneNumber == null) {
// No reformatted number, use the original
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
if(phoneNumber.equals("1234")){ // DialedNumber checking.
// My app will bring up, so cancel the broadcast
setResultData(null);
// Start my app
Intent i=new Intent(context,MainActivity.class);
i.putExtra("extra_phone", phoneNumber);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Don't forget to register this receiver in your manifest
<receiver android:name="MyOutgoingCallHandler">
<intent-filter >
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
Also, include the permission:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
Now, if you are ignoring the number checking in receiver, you'll get dialed number inside your MainActivity,
String phone=getIntent().getStringExtra("extra_phone");
if(!phone.equals(null)){
Toast.makeText(getBaseContext(), phone, Toast.LENGTH_LONG).show();
}
来源:https://stackoverflow.com/questions/19950623/launch-application-using-dial-pad-in-android