2014-10-14 5 views
0

특정 시간 후에 자동 SMS를 보내는 앱이 있습니다. 항상 백그라운드에서 실행하고 휴대 전화를 다시 시작하면 자동으로 프로세스가 시작됩니다. 그것은 Activity로 확장 할 때 잘 동작했습니다. 서비스로 어떻게 시작해야하는지 친절하게 알려주십시오.android : 서비스 시작 방법

서비스 클래스의 코드

public class MainActivity extends Service { 

@Override 
public void onCreate() { 
    //super.onCreate(savedInstanceState); 
    //setContentView(R.layout.activity_main); 
    startLocationTracking(); 
} 

private void startLocationTracking() 
{ 
    AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE); 

    Intent alarmintent1=new Intent(MainActivity.this, AlarmReceiver.class); 

    PendingIntent sender1=PendingIntent.getBroadcast(MainActivity.this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA); 

    try { 
     am.cancel(sender1); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("exjfkd"+e); 
    } 

    Calendar cal = Calendar.getInstance(); 
    cal.add(Calendar.SECOND,5); 


    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*180, sender1); 
    System.out.println("set timer"); 
} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 

} 

초 클래스

public class AlarmReceiver extends BroadcastReceiver{ 

long time = 180 * 1000; 
long distance = 10; 

@SuppressLint("NewApi") 

@Override 
public void onReceive(final Context context, Intent intent) { 

    System.out.println("alarm receiver...."); 

    LocationManager locationManager = (LocationManager)context 
      .getSystemService(Context.LOCATION_SERVICE); 


    Criteria criteria = new Criteria(); 
    String provider = locationManager.getBestProvider(criteria, true); 
    locationManager.requestLocationUpdates(provider, time, 
      distance, locationListener); 

    Location location = locationManager.getLastKnownLocation(provider); 

    String phoneNo = "+96987978"; 
    String Text = "Latitude = " + location.getLatitude() +" Longitude = " + location.getLongitude(); 

    try { 
    SmsManager smsManager = SmsManager.getDefault(); 
    smsManager.sendTextMessage(phoneNo, null, Text, null, null); 
    Log.i("Send SMS", ""); 

    Toast.makeText(context, "message sent", Toast.LENGTH_SHORT).show(); 

} catch (Exception e) { 
    Toast.makeText(context, "SMS faild, please try again.", 
    Toast.LENGTH_LONG).show(); 
    e.printStackTrace(); 
} 

} 

LocationListener locationListener = new LocationListener() { 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 

    } 
}; 



} 

AndroidManifest를 파일

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 



    <service android:enabled="true" 
     android:name="com.example.locationupdates.services.MainActivity" > 
    <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

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

    <receiver android:name="com.example.locationupdates.AlarmReceiver" > 
    <intent-filter android:priority="100"> 
    <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
</intent-filter> 
    </receiver> 
</application> 

+0

이미이 링크를 통해 묻습니다. 'http://stackoverflow.com/questions/5290141/android-broadcastreceiver -on-startup ' –

+0

다음 링크를 참조하여 도움을 받으실 수 있습니다. http://stackoverflow.com/questions/18299700/start-my-service-on-phone-restart-in-android – MFP

답변

0

이런 식으로 뭔가를 시도 당신이 추가, 이것은 방송 수신기에게 있습니다

public class HandlerService extends Service 
{ 
    private final IBinder mBinder = new MyBinder(); 
    @Override 
    public IBinder onBind(Intent arg0) 
    { 
     return mBinder; 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     //your stuff 

     return super.onStartCommand(intent, flags, startId); 
    } 

    @Override 
    public void onCreate() { 
     Log.d("oncreated", "oncreated"); 
    } 

    @Override 
    public void onDestroy() { 

    } 

    public class MyBinder extends Binder { 
     HandlerService getService() { 
     return HandlerService.this; 
     } 
    } 

} 

HandlerService가

public class BootCompleteReceiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context context, Intent intent) { 

      Log.d("BootCompleteReceiver", "BootCompleteReceiver"); 

      Intent service = new Intent(context, HandlerService.class); 
      context.startService(service); 

     } 
} 

장군 부통령. 서비스에 대한 새 클래스를 만들고이를 매니페스트 파일에 등록하십시오. 응용 프로그램 노드 내부에 해당 행을 추가하십시오. come.code가 BootCompleteReceiver 클래스의 패키지입니다

<receiver android:name="come.code.BootCompleteReceiver" > 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter> 
</receiver> 

+0

이 파일을 매니페스트 파일에 추가하는 방법을 보여줄 수 있습니다. – Andrain

+0

나는 대답을 편집했습니다 –

+0

mainActivity의 코드를 변경해야합니까? 아니면 맞습니까? – Andrain

1
당신은 Boot Receiver 리를 만들 필요가

의 코드 KE이 : ​​

public class MyReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

    Intent myIntent = new Intent(context, YourService.class); 
    context.startService(myIntent); 
    } 
} 

그리고 AndroidManifest.xml

<!-- Declaring broadcast receiver for BOOT_COMPLETED event --> 
    <receiver android:name=".MyReceiver " android:enabled="true" android:exported="false"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED"/> 
     </intent-filter> 
    </receiver> 

</application> 

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
+0

감사합니다. 수업이 맞습니까? – Andrain

+0

또한 AlarmManager 이벤트가 브로드 캐스트에서 발생할 때마다 트리거되는 서비스에서 onStart() 메서드를 재정의해야합니다. –

+0

답변을 시도했지만 결과가 표시되지 않습니다. 어떻게하면 onStart() 메서드를 재정의하는 지 보여 줄 수 있습니까? – Andrain

0

당신은 당신이 그것을

와 상호 작용 유지하려는 경우 서비스가 정말 시작할 때 확인하고 결합하는 ServiceConnection을 사용할 수 있습니다
private Service mService; 

    private ServiceConnection mServiceConnexion = new ServiceConnection() { 

     @Override 
     public void onServiceDisconnected(ComponentName name) { 
     mService = null; 
     } 

     @Override 
     public void onServiceConnected(ComponentName name, IBinder binder) { 
      if (mService == null) { 
      mService = (Service) ((Service.Binder) binder).getServiceInstance(); 
      } 
      Intent intent = new Intent(ActivityPlayer.this, ServiceStreaming.class); 
      startService(intent); 
     } 
    }; 


    private void bindService() { 
     if (mServiceConnexion != null) { 
     bindService(new Intent(Activity.this, Service.class), mServiceConnexion, Context.BIND_AUTO_CREATE); 
     } 
    } 

그냥 당신이 onPause()

주에서 바인딩을 해제 할 것,이 경우에서 onCreate 나 onResume()에서 bindServices()를 호출 당신은 캘리포니아 수 당신이 원하는만큼 StartService()를 해줄 수 있습니다. 매번 onStartCommand()를 호출 할 것입니다.