2014-10-02 5 views
0

Я видел, как различные люди реализуют onReceive() в своем классе, который расширяет BroadcastReceiver. Но есть ли способ реализовать onReceive() в другом классе, чем MainActivity, когда кнопка нажата в MainActivity? Если это возможно, как я могу позвонить onReceive() при нажатии кнопки? У меня есть приемник, реализованный в моем файле AndroidManifest, так что это будет срабатывать и при нажатии кнопки и вызывается onReceive()?Реализовать onReceive() при нажатии кнопки в MainActivity

MainActivity класс -

public class MainActivity extends Activity { 

Button activateButton; 
LocationManager mManager; 
AlertDialog.Builder box; 
BroadcastReceiver b; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    activateButton = (Button)findViewById(R.id.activate); 
    activateButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

       DialogBox(); 
     } 
    }); 

} 

protected void DialogBox() { 
    box = new AlertDialog.Builder(this); 
    box.setTitle("Reject incoming calls?"). 
      setMessage("On activation, your phone will reject all incoming calls").setCancelable(false) 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        Intent intent = new Intent("android.intent.action.PHONE_STATE"); 
        MainActivity.this.sendBroadcast(intent); 
       } 
      }).setNegativeButton("No", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      dialog.cancel(); 
     } 
    }); 
    final AlertDialog alert = box.create(); 
    alert.show(); 

} 

RejectCall класс -

public class RejectCall extends BroadcastReceiver { 

public void onReceive(Context context, Intent intent) { 
    Log.i("RejectClass", "Triggered"); 
    ITelephony telephonyService; 
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 
    try { 
     Class c = Class.forName(tm.getClass().getName()); 
     Method m = c.getDeclaredMethod("getITelephony"); 
     m.setAccessible(true); 
     telephonyService = (ITelephony) m.invoke(tm); 
     //telephonyService.silenceRinger(); 
     telephonyService.endCall(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

}

AndroidManifest.xml -

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.scimet.admin.driveon" > 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 


<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <receiver android:name=".RejectCall"> 
     <intent-filter> 
      <action android:name="android.intent.action.PHONE_STATE"/> 
     </intent-filter> 
    </receiver> 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

Я также определил интерфейс для ITelephony.

ответ

1

можно реализовать диалог, чтобы сохранить настройки для отклонения вызовов:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

    protected void DialogBox() { 
     box = new AlertDialog.Builder(this); 
     box.setTitle("Reject incoming calls?"). 
       setMessage("On activation, your phone will reject all incoming calls").setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         preferences.edit().putBoolean(PREF_REJECT_CALLS, true).commit(); 
        } 
       }).setNegativeButton("No", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       preferences.edit().putBoolean(PREF_REJECT_CALLS, false).commit();     
       dialog.cancel(); 
      } 
     }); 
     final AlertDialog alert = box.create(); 
     alert.show(); 

    } 



public class RejectCall extends BroadcastReceiver { 

public void onReceive(Context context, Intent intent) { 

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

    // If the value in preferences is false, do not reject the calls 
    if(!preferences.getBoolean(PREF_REJECT_CALLS, false)){ 
     return; 
    } 

    Log.i("RejectClass", "Triggered"); 
    ITelephony telephonyService; 
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 
    try { 
     Class c = Class.forName(tm.getClass().getName()); 
     Method m = c.getDeclaredMethod("getITelephony"); 
     m.setAccessible(true); 
     telephonyService = (ITelephony) m.invoke(tm); 
     //telephonyService.silenceRinger(); 
     telephonyService.endCall(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
+0

Привет, мой телефон просто падает на реализацию этого пути. Телефон перезагрузится. Я отредактирую описание и отправлю свой код. – Slay

+0

См. Мое редактирование, вам нужно сохранить настройки, чтобы включать или выключать отклонение. Broadcast отправляется системой при получении вызова. – JanKnotek

+0

Не должно быть «preferences.edit(). PutBoolean (« PREF_REJECT_CALLS », true) .commit(); ' Извините, я мог быть совершенно неправ. Кроме того, как это сохранить предпочтение? – Slay

Смежные вопросы