安卓面试集锦

  • 再按一次退出

  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. }

来自为知笔记(Wiz)

时间: 2024-10-11 14:06:44

安卓面试集锦的相关文章

安卓面试备考题收集

最近要参加面试,网上找了一些题来备着,大家也来学习学习吧,话说平时还真有些东西不知道... 面试题一:AIDL的全称是什么?如何工作? Android interface definition language (android接口定义语言) , 用来跨进程的访问方法, 像 游戏中调用支付宝接口就是用的这个. 访问远程的服务的方法. 如何工作. 面试题二:Android程序运行时权限与文件系统权限的区别? 程序运行时权限:Android程序执行需要读取到安全敏感项必需在androidmanife

安卓面试易考题(二)

这是延续上一部分的知识,依然是面试题,进入正题: 面试题一:谈谈你对Activity的理解: 这是考官希望你把自己的心得,做项目的时候的体会写出来:我们可以答Activity异常被系统回收的时候怎么处理的,然后可以讲讲Activity的生命周期. 面试题二:Service是否运行在主线程?能否在Service里面执行耗时的操作? 答:service是默认运行在主线程的,很多人觉得是后台服务就觉得应该是在子线程,其实不是,所以我们不能在里面执行耗时的操作,因为会产生ANR异常.我们要做耗时的操作要

iOS 面试集锦2

4.写一个setter方法用于完成@property (nonatomic,retain)NSString *name,写一个setter方法用于完成@property(nonatomic,copy)NSString *name - (void) setName:(NSString*) str { [str retain]; [name release]; name = str; } - (void)setName:(NSString *)str { id t = [str copy]; [na

iOS 面试集锦

是第一篇: 1.Difference between shallow copy and deep copy??浅复制和深复制的区别??答案:浅层复制:只复制指向对象的指针,而不复制引用对象本身.?深层复制:复制引用对象本身.?意思就是说我有个A对象,复制一份后得到A_copy对象后,对于浅复制来说,A和A_copy指向的是同一个内存资源,复制的只不过是是一个指针,对象本身资源?还是只有一份,那如果我们对A_copy执行了修改操作,那么发现A引用的对象同样被修改,这其实违背了我们复制拷贝的一个思想

iOS面试集锦3

1.写一个NSString类的实现 + (id)initWithCString:(c*****t char *)nullTerminatedCString encoding:(NSStringEncoding)encoding; + (id) stringWithCString: (c*****t char*)nullTerminatedCString encoding: (NSStringEncoding)encoding { NSString  *obj; obj = [self alloc

BAT面试必知:Dubbo&amp;Zookeeper面试集锦

技术面试是每一位程序员都会经历的一件事情,技术面试官会通过自己的方式去考察程序员的技术功底与基础理论知识,这个过程被有的程序员成为"造火箭式的技术轰炸",不同程序员的面试经历与体验也是千差万别,各种奇怪,奇葩的情况也是层出不穷. 小编准备了一些关于Dubbo,Zookeeper面试集锦,大部分题目不设标准答案,需要答案的提示可以加小编QQ群937053620,获取! Dubbo面试题锦集 1.默认也推荐使用netty框架,还有mina. 2.默认是阻塞的,可以异步调用,没有返回值的可以

安卓 面试经验

韩梦飞沙  韩亚飞  [email protected]  yue31313  han_meng_fei_sha #Alibaba 一面 说一下你怎么学习安卓的? 项目中遇到哪些问题,如何解决的? Android事件分发机制? 三级缓存底层实现? HashMap底层实现,hashCode如何对应bucket? Java的垃圾回收机制,引用计数法两个对象互相引用如何解决? 用过的开源框架的源码分析 Acticity的生命周期,Activity异常退出该如何处理? tcp和udp的区别,tcp如何保

C++面试集锦( 面试被问到的问题 )

1. C 和 C++ 区别      2. const 有什么用途     主要有三点: 1:定义只读变量,即常量 2:修饰函数的参数和函数的返回值 3: 修饰函数的定义体,这里的函数为类的成员函数,被const修饰的成员函数代表不修改成员变量的值   3. 指针和引用的区别     1:引用是变量的一个别名,内部实现是只读指针 2:引用只能在初始化时被赋值,其他时候值不能被改变,指针的值可以在任何时候被改变 3:引用不能为NULL,指针可以为NULL 4:引用变量内存单元保存的是被引用变量的地

安卓面试精华(Activity部分)

过几天小弟要去面试了,当然免不了要好好复习下功课,其实很多东西也不是特别清楚,今天都当作一个回顾和巩固,希望我的这篇文章能对即将去找工作的同学有所帮助. 1. Q:什么是activity? 虽然这个问题现在不流行问了,但是还是做好准备,有备无患嘛. A: 1).activity是四大组件之一,一般情况下,一个和用户交互的界面就对应有一个activity. 2).Activity是Context的子类,同时它实现了Window.callback和keyEvent.callback,正因为如此,人们