Created
October 21, 2023 12:30
-
-
Save kwmt/e23004c96816ef08e600d279f69468c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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