Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kwmt/e23004c96816ef08e600d279f69468c0 to your computer and use it in GitHub Desktop.
Save kwmt/e23004c96816ef08e600d279f69468c0 to your computer and use it in GitHub Desktop.
// import は省略
public class MainActivity extends Activity {
TextView mTextView;
Button mButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.hello);
mButton = (Button) findViewById(R.id.startservice);
// ボタンにリスナーを設定
mButton.setOnClickListener(new startClickListener());
}
// リスナー
public class startClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
// bindService()をコール
serviceConnect();
}
}
public void serviceConnect() {
// public abstract boolean bindService (Intent service, ServiceConnection conn, int flags)
bindService(new Intent(com.google.android.apps.gddquiz.IQuizService.class.getName()), // Intent
conn, // ServiceConnection
BIND_AUTO_CREATE); // int:automatically create the service as long as the binding exists.
}
// 以下はServiceにバインドするとき、バインドして何がしたいのかの設定
IQuizService mQuizService;
Boolean mStartedService = false;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("ServiceConnection", "onServiceConnected Start");
mQuizService = com.google.android.apps.gddquiz.IQuizService.Stub.asInterface(service);
mStartedService = true;
getStringInQuizService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mQuizService = null;
mStartedService = false;
}
};
public void getStringInQuizService() {
super.onResume();
if (mQuizService != null) {
try {
String ans = mQuizService.getCode().toString();
mTextView.setText((String) ans);
Log.d("AnsCode", ans); // 答えをLogCatに出力
//Toast.makeText(this, ans, Toast.LENGTH_LONG).show(); // 先にToast表示したけど、コピペできないじゃん。。。
} catch (RemoteException e) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment