安卓面试知识点

再按一次退出

     Handler handler = new Handler(Looper.getMainLooper());
        if (isExit) {
            handler.removeCallbacks(onBackTimeThread);
            isExit = false;
            finish();
        } else {
            isExit = true;
            Toast.makeText(this, "再按一下退出", Toast.LENGTH_SHORT).show();
            handler.postDelayed(onBackTimeThread, 3000);
        }

网络请求

    private String requestData(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("GET");  // GET POST
            connection.connect();
            int responseCode = connection.getResponseCode();
            //String responseMessage = connection.getResponseMessage();
            String result = null;
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream, "UTF-8");
                char[] buffer = new char[1024];
                reader.read(buffer);
                result = new String(buffer);
            } else {

            }
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("myLog","非法的uri");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

异步任务的简单封装

public interface DataLoader<Result> {
    public Result loadData();;
    public void updateUi(Result result);
}
public class SimpleAsyncTask<Result> extends AsyncTask<Void,Integer,Result>{

    private Context context;
    private ProgressDialog mProgressDialog;
    private String message;
    private DataLoader<Result> loader;

    public SimpleAsyncTask(Context context,int msgID,DataLoader<Result> loader){
        this.context=context;
        message=context.getString(msgID);
        this.loader=loader;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog=new ProgressDialog(context);
        mProgressDialog.setMessage(message);
        mProgressDialog.show();
    }

    @Override
    protected Result doInBackground(Void... params) {
        try{
            return loader.loadData();
        }catch (Exception e){
            mProgressDialog.dismiss();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Result result) {
        loader.updateUi(result);
        mProgressDialog.dismiss();
        super.onPostExecute(result);
    }
}

服务

Service生命周期的两种方式
- 1.context.startService() -> onCreate() -> onStartCommand() -> Service running ->context.stopService() -> onDestroy() -> Service stop
- 2.bindService() ——> onCreate() ——> onBind() ——> Service running ——>
onUnbind() ——> onDestroy() ——> Service stop

public class MusicService extends Service {
    public static final String TAG = MusicService.class.getSimpleName();
    private MediaPlayer mMediaPlayer;
    private MyBinder mMyBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = MediaPlayer.create(this, R.raw.chuxuezhe);

        //通知栏
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, ServiceTestActivity.class), 0);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My notification")
                        .setContentText("Hello World!");
        mBuilder.setContentIntent(pendingIntent);
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(1, mBuilder.build());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        mMediaPlayer.start();
        return mMyBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mMediaPlayer.start();
        return START_NOT_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMediaPlayer.stop();
        stopForeground(true);
    }


    public class MyBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

}
public class ServiceTestActivity extends AppCompatActivity implements View.OnClickListener{

    private Button start_service,stop_service;
    private boolean isBind = false ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_test);
        start_service= (Button) findViewById(R.id.start_service);
        stop_service= (Button) findViewById(R.id.stop_service);
        start_service.setOnClickListener(this);
        stop_service.setOnClickListener(this);
    }

    private ServiceConnection mServiceConnection=new ServiceConnection() {
        private MusicService mMusicService;
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MusicService.MyBinder binder= (MusicService.MyBinder) iBinder;
            mMusicService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mMusicService=null;
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.start_service:
                isBind =bindService(new Intent(ServiceTestActivity.this, MusicService.class),mServiceConnection,BIND_AUTO_CREATE);
                //startService(new Intent(ServiceTestActivity.this, MusicService.class));
                break;
            case R.id.stop_service:
                if (isBind) {
                    unbindService(mServiceConnection);
                    isBind = false;
                }
                //stopService(new Intent(ServiceTestActivity.this, MusicService.class));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBind) {
            unbindService(mServiceConnection);
            isBind = false;
        }
    }
}

广播

public class TestBroadcastReceiver extends BroadcastReceiver {
    public static final String TAG = "myLog";
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent!=null){
            if(TextUtils.equals(intent.getAction(), SendBroadcastActivity.COM_XHB_ONLYSTAR)){
                Log.i(TAG, "onReceive:action "+intent.getAction());
                Log.i(TAG, "onReceive:broadcast "+intent.getStringExtra("toast"));
            }
        }
    }
}
public class SendBroadcastActivity extends AppCompatActivity {

    public static final String COM_XHB_ONLYSTAR = "com.xhb.onlystar";
    private TestBroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    private Button mSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_broadcast);
        //注册需要一个IntentFilter
        mFilter = new IntentFilter();
        mFilter.addAction(COM_XHB_ONLYSTAR);
        //注册需要一个广播接收器
        mReceiver = new TestBroadcastReceiver();

        mSend = (Button) findViewById(R.id.send);
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setAction(COM_XHB_ONLYSTAR);
                intent.putExtra("toast","this is the broadcast");
                sendBroadcast(intent);//发送多个广播能全部接收到
                //sendOrderedBroadcast(intent);//按照优先级接收
               // LocalBroadcastManager
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        //注册
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //取消注册
        unregisterReceiver(mReceiver);
    }
}

底部导航栏的实现

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:background="@color/gray" />

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"/>

</LinearLayout>
public class TestTabHostActivity extends AppCompatActivity {

    private FragmentTabHost mTabhost;
    private List<Tab> mTabs = new ArrayList<Tab>(5);
    private LayoutInflater mInflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_tab_host);
        initView();
    }

    private void initView() {
        Tab tab_home = new Tab(HomeFragment.class, R.string.home, R.drawable.selector_icon_home);
        Tab tab_hot = new Tab(HomeFragment.class, R.string.hot, R.drawable.selector_icon_hot);
        Tab tab_category = new Tab(HomeFragment.class, R.string.catagory, R.drawable.selector_icon_category);
        Tab tab_cart = new Tab(HomeFragment.class, R.string.cart, R.drawable.selector_icon_cart);
        Tab tab_mine = new Tab(HomeFragment.class, R.string.mine, R.drawable.selector_icon_mine);

        mTabs.add(tab_home);
        mTabs.add(tab_hot);
        mTabs.add(tab_category);
        mTabs.add(tab_cart);
        mTabs.add(tab_mine);

        mInflater = LayoutInflater.from(this);
        mTabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);//必须要

        for (Tab tab : mTabs) {
            TabHost.TabSpec tabSpec = mTabhost.newTabSpec(getString(tab.getTitle()));
            tabSpec.setIndicator(buildIndicator(tab));
            mTabhost.addTab(tabSpec, tab.getFragment(), null);
        }
        mTabhost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);//取消item之间的分割线
        mTabhost.setCurrentTab(0);//默认选择第一个
    }

    //得到indicator
    private View buildIndicator(Tab tab) {
        View view = mInflater.inflate(R.layout.tab_indicator, null);
        ImageView img = (ImageView) view.findViewById(R.id.icon_tab);
        TextView text = (TextView) view.findViewById(R.id.txt_indicator);
        img.setBackgroundResource(tab.getIcon());
        text.setText(tab.getTitle());
        return view;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值