2016-07-02 2 views
0

односторонняя связь от деятельности до обслуживания и обслуживания выполняется неопределенно до тех пор, пока действие не приведет к ее прекращению.Лучший способ сделать только один способ i.e для обслуживания связи?

+0

см ' Контекст # startService() ' – pskink

+0

не могли бы вы объяснить? –

+0

что неясно после чтения 'startService()' javadocs? – pskink

ответ

0

Вы можете использовать широковещательный приемник для связи между услугами и деятельностью

Ваша служба должна быть такой: -

public class MyService extends Service { 

private static final String TAG = "com.example.ServiceExample"; 

@Override 
    public void onCreate() { 
    Log.i(TAG, "Service onCreate"); 
} 

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


    //SendBroadCast to Activity 
    Intent intent = new Intent("my-event"); 
    intent.putExtra("message", "data"); 
    sendBroadcast(intent); 
    return Service.START_STICKY; 
} 

@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    Log.i(TAG, "Service onBind"); 
    return null; 
} 

@Override 
    public void onDestroy() { 
    Log.i(TAG, "Service onDestroy"); 
} 
} 

Ваша активность должна быть такой: -

public class BindingActivity extends Activity { 


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

@Override 
protected void onStart() { 
    super.onStart(); 

} 

@Override 
protected void onStop() { 
    super.onStop(); 

} 

/** Called when a button is clicked (the button in the layout file attaches to 
    * this method with the android:onClick attribute) */ 
public void onButtonClick(View v) { 

} 

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()  { 
@Override 
public void onReceive(Context context, Intent intent) { 
    // Extract data included in the Intent 
    String message = intent.getStringExtra("message"); 
    Log.d("receiver", "Got message: " + message); 
} 
}; 

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

// Register mMessageReceiver to receive messages. 
registerReceiver(mMessageReceiver, 
    new IntentFilter("my-event")); 
    } 

@Override 
protected void onPause() { 
    // Unregister since the activity is not visible 
    unregisterReceiver(mMessageReceiver); 
     super.onPause(); 
      } } 

       } 
+0

Служба не предназначена для длительных задач? см. также http://techtej.blogspot.hk/2011/03/android-thread-constructspart-4.html – David

+1

https://developer.android.com/training/best-background.html – Karacken

+0

@kracken этот ограниченный сервис не работает неопределенно. что мне делать? –

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