package com.ct.mytestsab; import com.ct.mytestsab.MyService.ServiceBinder; import android.os.Bundle; import android.os.IBinder; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.view.Menu; public class MainActivity extends Activity { private ServiceBinder binder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = new Intent(this,MyService.class); bindService(intent, connection, BIND_AUTO_CREATE); } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub binder = (ServiceBinder)service; int count = binder.getCount(); System.out.println(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.ct.mytestsab; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyBroadCast extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub int count = intent.getIntExtra("count", 0); Toast.makeText(context, count+"", 0).show(); } }
package com.ct.mytestsab; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; public class MyService extends Service{ boolean flag = true; int count = 0; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return new ServiceBinder(); } public class ServiceBinder extends Binder{ public int getCount() { return count; } } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (flag) { count++; if(count%5==0){ Intent intent = new Intent("com.ct.mytestsab.count"); intent.putExtra("count", count); sendBroadcast(intent); } try { Thread.sleep(500); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } }).start(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); flag = false; } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); } }
另外一个例子(F:\java\DynamicUI)