0

전화가 걸려 올 때 토스트를 표시하고 싶은 안드로이드 앱을 개발 중입니다. 화면 잠금이 해제되면 앱이 잘 돌아갑니다. 하지만 홈 화면이 잠겨있을 때 아무 것도 표시하지 않으면 누구든지 나를 도울 수 있습니다. 여기 Android : 화면이 잠겨있을 때 서비스를 실행하는 방법?

이 통화를

package com.example.lenovo.call_toast; 

    import android.app.Service; 
    import android.content.Intent; 
    import android.os.IBinder; 


    public class CallDetectService extends Service { 
     private CallHelper callHelper; 

     public CallDetectService() { 
     } 

     @Override 
     public int onStartCommand(Intent intent, int flags, int startId) { 
      callHelper = new CallHelper(this); 

      int res = super.onStartCommand(intent, flags, startId); 
      callHelper.start(); 
      return res; 
     } 

     @Override 
     public void onDestroy() { 
      super.onDestroy(); 

      callHelper.stop(); 
     } 

     @Override 
     public IBinder onBind(Intent intent) { 
      // not supporting binding 
      return null; 
     } 
    } 

을 감지 내 서비스 내 전체 코드

package com.example.lenovo.call_toast; 

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.os.PowerManager; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 


public class MainActivity_service extends Activity { 

    private boolean detectEnabled; 

    private TextView textViewDetectState; 
    private Button buttonToggleDetect; 
    private Button buttonExit; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     PowerManager mgr = (PowerManager)getSystemService(Context.POWER_SERVICE); 
     PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock"); 
     wakeLock.acquire(); 

     textViewDetectState = (TextView) findViewById(R.id.textViewDetectState); 

     buttonToggleDetect = (Button) findViewById(R.id.buttonDetectToggle); 
     buttonToggleDetect.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       setDetectEnabled(!detectEnabled); 
      } 
     }); 

     buttonExit = (Button) findViewById(R.id.buttonExit); 
     buttonExit.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       setDetectEnabled(false); 
       MainActivity_service.this.finish(); 
      } 
     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 

    private void setDetectEnabled(boolean enable) { 
     detectEnabled = enable; 

     Intent intent = new Intent(this, CallDetectService.class); 
     if (enable) { 
      // start detect service 




      startService(intent); 

      buttonToggleDetect.setText("Turn off"); 
      textViewDetectState.setText("Detecting"); 
     } 
     else { 
      // stop detect service 
      stopService(intent); 

      buttonToggleDetect.setText("Turn on"); 
      textViewDetectState.setText("Not detecting"); 
     } 
    } 

} 

입니다 그리고 이것은 다른 클래스

package com.example.lenovo.call_toast; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.telephony.PhoneStateListener; 
import android.telephony.TelephonyManager; 
import android.util.Log; 
import android.widget.Toast; 


public class CallHelper { 

    /** 
    * Listener to detect incoming calls. 
    */ 
    private class CallStateListener extends PhoneStateListener { 
     @Override 
     public void onCallStateChanged(int state, String incomingNumber) { 

      switch (state) { 
      case TelephonyManager.CALL_STATE_RINGING: 
       // called when someone is ringing to this phone 

       Toast.makeText(ctx, 
         "Incoming: " +incomingNumber, 
         Toast.LENGTH_LONG).show(); 

       break; 

      } 
     } 
    } 

    /** 
    * Broadcast receiver to detect the outgoing calls. 
    */ 
    public class OutgoingReceiver extends BroadcastReceiver { 
     public OutgoingReceiver() { 
     } 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); 
      Log.e("onCallStateChanged: ",number); 
      Toast.makeText(ctx,"Outgoing: "+number, 
        Toast.LENGTH_LONG).show(); 
     } 

    } 

    private Context ctx; 
    private TelephonyManager tm; 
    private CallStateListener callStateListener; 

    private OutgoingReceiver outgoingReceiver; 

    public CallHelper(Context ctx) { 
     this.ctx = ctx; 

     callStateListener = new CallStateListener(); 
     outgoingReceiver = new OutgoingReceiver(); 
    } 

    /** 
    * Start calls detection. 
    */ 
    public void start() { 
     tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); 
     tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE); 

     IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL); 
     ctx.registerReceiver(outgoingReceiver, intentFilter); 

    } 

    /** 
    * Stop calls detection. 
    */ 
    public void stop() { 
     tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE); 
     ctx.unregisterReceiver(outgoingReceiver); 
    } 

} 

입니다 그리고 여기에 매니페스트 파일

입니다
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.lenovo.call_toast"> 

    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK"/> 



    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity_service"> 
      <intent-filter>--> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <!--<activity android:name=".MyCustomDialog"--> 
      <!--android:theme="@android:style/Theme.Dialog"--> 
      <!--android:noHistory="true"--> 
      <!--/>--> 
     <!--&lt;!&ndash;<receiver android:name=".CallReceiver" >&ndash;&gt;--> 
      <!--&lt;!&ndash;<intent-filter>&ndash;&gt;--> 
       <!--&lt;!&ndash;<action android:name="android.intent.action.PHONE_STATE" />&ndash;&gt;--> 
      <!--&lt;!&ndash;</intent-filter>&ndash;&gt;--> 
      <!--&lt;!&ndash;<intent-filter>&ndash;&gt;--> 
       <!--&lt;!&ndash;<action android:name="android.intent.action.NEW_OUTGOING_CALL" />&ndash;&gt;--> 
      <!--&lt;!&ndash;</intent-filter>&ndash;&gt;--> 
     <!--</receiver>--> 

     <service android:name=".CallDetectService" 

      android:enabled="true" 
      android:exported="false"/> 

    </application> 


</manifest> 

답변

0

이제 안드로이드가 배터리 드레인을 처리하기 때문에 화면이 잠겨있을 때 작성한 코드는 새 장치에서 작동하지 않습니다. 따라서 수신기로 백그라운드 서비스를 실행할 수 없습니다. 지속적으로 수신기로 실행하기보다는

  • 1 단계) 확인 수신기
  • 2 단계) 서비스/활동이나 onReceive 방법에 대한 모든 작업을 시작 :이 작업을 수행하려면하지만 여전히, 다음 단계를 수행 이 작업을 수행하기위한 것입니다.

처럼 :

@Override 
     public void onReceive(Context context, Intent intent) { 
      // TODO Auto-generated method stub 
    { 

    Bundle bb = intent.getExtras(); 
      String state = bb.getString(TelephonyManager.EXTRA_STATE); 
      if ((state != null)&& (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)))  
      { 
       incommingNumber = bb.getString(TelephonyManager.EXTRA_INCOMING_NUMBER); 
    blockCall(context, bb); 
    } 
    } 

    public void blockCall(Context c, Bundle b) 
    { 

     TelephonyManager telephony = (TelephonyManager) 
     c.getSystemService(Context.TELEPHONY_SERVICE); 
     try { 
     Class cls = Class.forName(telephony.getClass().getName()); 
     Method m = cls.getDeclaredMethod("getITelephony"); 
     m.setAccessible(true); 
     telephonyService = (ITelephony) m.invoke(telephony); 
     //telephonyService.silenceRinger(); 
     telephonyService.endCall(); 

      new SendValue(c,incommingNumber); 

     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
} 

경우 SendValue (컨텍스트 C, 문자열 incomingNumber); 호출이 수신 될 때 필요한 작업을 수행하고 호출을받을 때 해당 값을 변경할 수 있도록 incommingNumber가 전역 String 변수 인 다른 Java 클래스의 생성자입니다.

+0

다음은 유용한 링크입니다. http://stackoverflow.com/questions/9029040/how-to-run-an-android-app-in-background/43555050#43555050 – user2288580

관련 문제