安卓面试集锦

Posted 星空守候

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓面试集锦相关的知识,希望对你有一定的参考价值。

  • 再按一次退出

  1. Handler handler = new Handler(Looper.getMainLooper());
  2. if (isExit) {
  3. handler.removeCallbacks(onBackTimeThread);
  4. isExit = false;
  5. finish();
  6. } else {
  7. isExit = true;
  8. Toast.makeText(this, "再按一下退出", Toast.LENGTH_SHORT).show();
  9. handler.postDelayed(onBackTimeThread, 3000);
  10. }
  • 网络请求

  1. private String requestData(String urlString) {
  2. try {
  3. URL url = new URL(urlString);
  4. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  5. connection.setConnectTimeout(30000);
  6. connection.setRequestMethod("GET"); // GET POST
  7. connection.connect();
  8. int responseCode = connection.getResponseCode();
  9. //String responseMessage = connection.getResponseMessage();
  10. String result = null;
  11. if(responseCode == HttpURLConnection.HTTP_OK){
  12. InputStream inputStream = connection.getInputStream();
  13. Reader reader = new InputStreamReader(inputStream, "UTF-8");
  14. char[] buffer = new char[1024];
  15. reader.read(buffer);
  16. result = new String(buffer);
  17. } else {
  18. }
  19. return result;
  20. } catch (MalformedURLException e) {
  21. e.printStackTrace();
  22. Log.i("myLog","非法的uri");
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. return null;
  27. }
  • 异步任务的简单封装

  1. public interface DataLoader<Result> {
  2. public Result loadData();;
  3. public void updateUi(Result result);
  4. }
  1. public class SimpleAsyncTask<Result> extends AsyncTask<Void,Integer,Result>{
  2. private Context context;
  3. private ProgressDialog mProgressDialog;
  4. private String message;
  5. private DataLoader<Result> loader;
  6. public SimpleAsyncTask(Context context,int msgID,DataLoader<Result> loader){
  7. this.context=context;
  8. message=context.getString(msgID);
  9. this.loader=loader;
  10. }
  11. @Override
  12. protected void onPreExecute() {
  13. super.onPreExecute();
  14. mProgressDialog=new ProgressDialog(context);
  15. mProgressDialog.setMessage(message);
  16. mProgressDialog.show();
  17. }
  18. @Override
  19. protected Result doInBackground(Void... params) {
  20. try{
  21. return loader.loadData();
  22. }catch (Exception e){
  23. mProgressDialog.dismiss();
  24. }
  25. return null;
  26. }
  27. @Override
  28. protected void onPostExecute(Result result) {
  29. loader.updateUi(result);
  30. mProgressDialog.dismiss();
  31. super.onPostExecute(result);
  32. }
  33. }
  • 服务

    Service生命周期的两种方式
  • 1.context.startService() -> onCreate() -> onStartCommand() -> Service running ->context.stopService() -> onDestroy() -> Service stop
  • 2.bindService() ——> onCreate() ——> onBind() ——> Service running ——>
    onUnbind() ——> onDestroy() ——> Service stop
  1. public class MusicService extends Service {
  2. public static final String TAG = MusicService.class.getSimpleName();
  3. private MediaPlayer mMediaPlayer;
  4. private MyBinder mMyBinder = new MyBinder();
  5. @Override
  6. public void onCreate() {
  7. super.onCreate();
  8. mMediaPlayer = MediaPlayer.create(this, R.raw.chuxuezhe);
  9. //通知栏
  10. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, ServiceTestActivity.class), 0);
  11. NotificationCompat.Builder mBuilder =
  12. new NotificationCompat.Builder(this)
  13. .setSmallIcon(R.mipmap.ic_launcher)
  14. .setContentTitle("My notification")
  15. .setContentText("Hello World!");
  16. mBuilder.setContentIntent(pendingIntent);
  17. NotificationManager mNotifyMgr =
  18. (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  19. mNotifyMgr.notify(1, mBuilder.build());
  20. }
  21. @Nullable
  22. @Override
  23. public IBinder onBind(Intent intent) {
  24. mMediaPlayer.start();
  25. return mMyBinder;
  26. }
  27. @Override
  28. public int onStartCommand(Intent intent, int flags, int startId) {
  29. mMediaPlayer.start();
  30. return START_NOT_STICKY;
  31. }
  32. @Override
  33. public boolean onUnbind(Intent intent) {
  34. return super.onUnbind(intent);
  35. }
  36. @Override
  37. public void onDestroy() {
  38. super.onDestroy();
  39. mMediaPlayer.stop();
  40. stopForeground(true);
  41. }
  42. public class MyBinder extends Binder {
  43. public MusicService getService() {
  44. return MusicService.this;
  45. }
  46. }
  47. }
  1. public class ServiceTestActivity extends AppCompatActivity implements View.OnClickListener{
  2. private Button start_service,stop_service;
  3. private boolean isBind = false ;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_service_test);
  8. start_service= (Button) findViewById(R.id.start_service);
  9. stop_service= (Button) findViewById(R.id.stop_service);
  10. start_service.setOnClickListener(this);
  11. stop_service.setOnClickListener(this);
  12. }
  13. private ServiceConnection mServiceConnection=new ServiceConnection() {
  14. private MusicService mMusicService;
  15. @Override
  16. public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  17. MusicService.MyBinder binder= (MusicService.MyBinder) iBinder;
  18. mMusicService = binder.getService();
  19. }
  20. @Override
  21. public void onServiceDisconnected(ComponentName componentName) {
  22. mMusicService=null;
  23. }
  24. };
  25. @Override
  26. public void onClick(View view) {
  27. switch (view.getId()){
  28. case R.id.start_service:
  29. isBind =bindService(new Intent(ServiceTestActivity.this, MusicService.class),mServiceConnection,BIND_AUTO_CREATE);
  30. //startService(new Intent(ServiceTestActivity.this, MusicService.class));
  31. break;
  32. case R.id.stop_service:
  33. if (isBind) {
  34. unbindService(mServiceConnection);
  35. isBind = false;
  36. }
  37. //stopService(new Intent(ServiceTestActivity.this, MusicService.class));
  38. break;
  39. }
  40. }
  41. @Override
  42. protected void onDestroy() {
  43. super.onDestroy();
  44. if (isBind) {
  45. unbindService(mServiceConnection);
  46. isBind = false;
  47. }
  48. }
  49. }
  • 广播

  1. public class TestBroadcastReceiver extends BroadcastReceiver {
  2. public static final String TAG = "myLog";
  3. @Override
  4. public void onReceive(Context context, Intent intent) {
  5. if(intent!=null){
  6. if(TextUtils.equals(intent.getAction(), SendBroadcastActivity.COM_XHB_ONLYSTAR)){
  7. Log.i(TAG, "onReceive:action "+intent.getAction());
  8. Log.i(TAG, "onReceive:broadcast "+intent.getStringExtra("toast"));
  9. }
  10. }
  11. }
  12. }
  1. public class SendBroadcastActivity extends AppCompatActivity {
  2. public static final String COM_XHB_ONLYSTAR = "com.xhb.onlystar";
  3. private TestBroadcastReceiver mReceiver;
  4. private IntentFilter mFilter;
  5. private Button mSend;
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_send_broadcast);
  10. //注册需要一个IntentFilter
  11. mFilter = new IntentFilter();
  12. mFilter.addAction(COM_XHB_ONLYSTAR);
  13. //注册需要一个广播接收器
  14. mReceiver = new TestBroadcastReceiver();
  15. mSend = (Button) findViewById(R.id.send);
  16. mSend.setOnClickListener(new View.OnClickListener() {
  17. @Override
  18. public void onClick(View view) {
  19. Intent intent=new Intent();
  20. intent.setAction(COM_XHB_ONLYSTAR);
  21. intent.putExtra("toast","this is the broadcast");
  22. sendBroadcast(intent);//发送多个广播能全部接收到
  23. //sendOrderedBroadcast(intent);//按照优先级接收
  24. // LocalBroadcastManager
  25. }
  26. });
  27. }
  28. @Override
  29. protected void onStart() {
  30. super.onStart();
  31. //注册
  32. registerReceiver(mReceiver, mFilter);
  33. }
  34. @Override
  35. protected void onStop() {
  36. super.onStop();
  37. //取消注册
  38. unregisterReceiver(mReceiver);
  39. }
  40. }
  • 底部导航栏的实现

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <FrameLayout
  7. android:id="@+id/realtabcontent"
  8. android:layout_width="fill_parent"
  9. android:layout_height="0dip"
  10. android:layout_weight="1"
  11. android:background="@color/gray" />
  12. <android.support.v4.app.FragmentTabHost
  13. android:id="@android:id/tabhost"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content"
  16. android:background="@color/white"/>
  17. </LinearLayout>
  1. public class TestTabHostActivity extends AppCompatActivity {
  2. private FragmentTabHost mTabhost;
  3. private List<Tab> mTabs = new ArrayList<Tab>(5);
  4. private LayoutInflater mInflater;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_test_tab_host);
  9. initView();
  10. }
  11. private void initView() {
  12. Tab tab_home = new Tab(HomeFragment.class, R.string.home, R.drawable.selector_icon_home);
  13. Tab tab_hot = new Tab(HomeFragment.class, R.string.hot, R.drawable.selector_icon_hot);
  14. Tab tab_category = new Tab(HomeFragment.class, R.string.catagory, R.drawable.selector_icon_category);
  15. Tab tab_cart = new Tab(HomeFragment.class, R.string.cart, R.drawable.selector_icon_cart);
  16. Tab tab_mine = new Tab(HomeFragment.class, R.string.mine, R.drawable.selector_icon_mine);
  17. mTabs.add(tab_home);
  18. mTabs.add(tab_hot);
  19. mTabs.add(tab_category);
  20. mTabs.add(tab_cart);
  21. mTabs.add(tab_mine);
  22. mInflater = LayoutInflater.from(this);
  23. mTabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
  24. mTabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);//必须要
  25. for (Tab tab : mTabs) {
  26. TabHost.TabSpec tabSpec = mTabhost.newTabSpec(getString(tab.getTitle()));
  27. tabSpec.setIndicator(buildIndicator(tab));
  28. mTabhost.addTab(tabSpec, tab.getFragment(), null);
  29. }
  30. mTabhost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);//取消item之间的分割线
  31. mTabhost.setCurrentTab(0);//默认选择第一个
  32. }
  33. //得到indicator
  34. private View buildIndicator(Tab tab) {
  35. View view = mInflater.inflate(R.layout.tab_indicator, null);
  36. ImageView img = (ImageView) view.findViewById(R.id.icon_tab);
  37. TextView text = (TextView) view.findViewById(R.id.txt_indicator);
  38. img.setBackgroundResource(tab.getIcon());
  39. text.setText(tab.getTitle());
  40. return view;
  41. }
  42. }




以上是关于安卓面试集锦的主要内容,如果未能解决你的问题,请参考以下文章

史上最全的2022年最新版Android安卓面试题集锦(含答案+源码)

代码面试集锦 1 - Uber

代码面试集锦 2 - Google

面试集锦

程序员面试必看!百度阿里腾讯……面试题和面试技巧集锦!

Android面试题基础集锦总结《二》