知识大杂烩

知识大杂烩

1.开启服务是Intent传递数据

  • 当开启一个Service时,如果要通过Intent去传递一些数据,在ServiceonStartCommand方法中有一个参数Intent,我们可以通过这个Intent来得到传递过来的数据
public class TestService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("@@@", intent.getStringExtra("aa"));
        return super.onStartCommand(intent, flags, startId);
    }
}

2.JVMDalvik虚拟机的区别

  • JVM是基于栈的架构(内存),编译过程为.java->.class->.jar
  • Dlvik(DVM)是基于寄存器的架构(CPU里面的存储空间,CPU操作数据比内存要快),编译过程为.java->.class->.dex->.odex
  • 一个应用,一个虚拟机实例,一个进程
    1. 每一个Android应用都运行在一个Dalvik虚拟机实例里,而每一个虚拟机实例都是一个独立的进程空间。每个进程之间可以通信(IPCBinder机制实现)。虚拟机的线程机制,内存分配和管理,Mutex等等都是依赖底层操作系统而实现的。
    2. 不同的应用在不同的进程空间里运行,当一个虚拟机关闭或意外中止时不会对其它 虚拟机造成影响,可以最大程度的保护应用的安全和独立运行。

3.Eclipse下关联support v4源码

  • libs目录下新建android-support-v4.jar.properties文件
    内容为src = D:\\Java\\adt-bundle-windows\\sdk\\extras\\android\\support\\v4\\src,(即指向adt中的support v4源码文件)
    然后刷新即可关联support v4源码。

4.自定义对话框

示例代码:

public void showDialog() {
    AlertDialog.Builder builder = new Builder(this);
    View view = View.inflate(this, R.layout.dialog, null);
    builder.setView(view);//将自定义的View设置到对话框中
    builder.show()
}

但是会发现对话框上面和下面都有一个小黑背景,这是因为对话框的默认背景是黑色的。那么怎么才让它去掉上面的黑背景呢?

public void showDialog() { 
    AlertDialog.Builder builder = new Builder(this);
    View view = View.inflate(this, R.layout.dialog, null);
    AlertDialog dialog = builder.create();
    dialog.setView(view,0,0,0,0);//设置填空的view据对话框的上下左右的距离
    dialog.show();
}

5.EditText添加内容改变的监听器

mEditText.addTextChangedListener(new TextWatcher() {
    //EditText中文本内容改变的时候自动调用的方法
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //这个CharSequence就是当前的文本输入框中的内容
        String address  = AddressDao.getAddress(s.toString());
        tv_numberquery_address.setText(address);
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    public void afterTextChanged(Editable s) {

    }
});

6.Android版本适配

对于Android的不同版本其功能可能不一样,我们要通过Build.VERSION.SDK_INT来判断当前系统的版本,从而根据不同的版本来设置不同的操作

这里以进入到Setting清楚缓存的界面为例

public void onClick(View v) {
    if (Build.VERSION.SDK_INT >= 9) {
        // 适合2.3 以及以上系统
        Intent intent = new Intent();
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("package:" + packname));
        startActivity(intent);
    } else {
        // 适合2.2 以及以下系统
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addCategory("android.intent.category.VOICE_LAUNCH");
        intent.putExtra("pkg", packname);
        startActivity(intent);
    }
}

7.手机重启

通过不断的new出来空白的Toast把系统弄崩溃,这样系统就会重启

public void click(View view) {
    while (true) {
        Toast toast = new Toast(this);
        toast.setView(new View(this));
        toast.show();
    }
}

8.adb shell 启动应用

启动的方法为

$ adb shell
$ am start -n {包(package)名}/{包名}.{活动(activity)名称}

由此计算器(calculator)的启动方法为:

am start -n com.android.calculator2/.Calculator

启动浏览器 :

am start -a android.intent.action.VIEW -d  http://www.google.cn/

拨打电话 :

am start -a android.intent.action.CALL -d tel:10086

9.启动APK默认Activity

public static void startApkActivity(final Context ctx, String packageName) {
        PackageManager pm = ctx.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(packageName, 0);
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setPackage(pi.packageName);

            List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);

            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                String className = ri.activityInfo.name;
                intent.setComponent(new ComponentName(packageName, className));
                ctx.startActivity(intent);
            }
        } catch (NameNotFoundException e) {
            Log.e("startActivity", e);
        }
    }
}

10.TextView行间距

Android系统中TextView默认显示中文时会比较紧凑,不是很美观。
为了让每行保持一定的行间距,可以设置属性android:lineSpacingExtraandroid:lineSpacingMultiplier

  1. android:lineSpacingExtra
    设置行间距,如”3dp”。

  2. android:lineSpacingMultiplier
    设置行间距的倍数,如”1.2″。

11.Android Pull Push命令

adb命令下pull的作用是从手机端向电脑端拷文件。
命令:

//将手机卡中的某个文本文件复制到电脑Dadb pull /sdcard/**.txt   D:\                         
adb pull /data/data/com.ifeng.newvideo/databases/ifengVideoV6.db e:/

push的作用和pull正好相反, 是从电脑端向手机复制文件的。下面是例子

adb push d:\lzd.doc /mnt/sdcard/jaj_training/fingerprint/

注意:这些命令都是在adb下用,而不是在shell中用。

12.Android 4.0横竖屏切换

==Android 2.3以前的横竖屏切换==

在Android 2.3平台上,我们可以需要设置界面的横竖屏显示时,可以在AndroidManifest.xml中,对Activity的属性添加以下代码:

android:configChanges="keyboardHidden|orientation"同时在Activity中覆写onConfigurationChanged方法

==Android 4.0以后的横竖屏切换==

当我们在4.0上像之前那样设置横竖屏时,会发现竟然没有效果,Activity依然走自己的生命周期,这是因为在API level 13以后Android做了修改了,当设备横竖屏切换时屏幕尺寸也改变了。因此,如果你想在API Level 13或者更高的环境下,像以前那样阻止设备的横竖屏切换,你需要在orientation后加上screenSize。也就说你要像这样声明:

android:configChanges="keyboardHidden|orientation|screenSize"

同时依然要在Activity中覆写onConfigurationChanged方法

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Log.i("TAG","I'm Android 4.0");
}

13.广播接收者中开启Activity

如果在一个不是Activity的上下文中(如服务或者广播接收者)中去开启一个Activity那么就必须设置intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这样才可以,不然会报错.因为Activity开启后必须要有一个Task栈,而在服务和广播接收者的上下文中并没有Task栈,所以我们必须要去指定一个新的栈。

public class OutCallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String number = getResultData();
        if("20182018".equals(number)){
            Intent loatFindIntent = new Intent(context,LostFindActivity.class);
            loatFindIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//用非Activity的context开启Activity时候必须加上这一句
            context.startActivity(loatFindIntent);
            setResultData(null);//设置外拨的电话号码为空.这样系统就不会启动拨号拨出了
        }
    }
}

14.onSaveInstanceState()以及onRestoreInstanceState()

  • Activity完整的生命周期
    onCreate() –> onStart() –> onRestoreInstanceState() –> onResume() –> onSaveInstanceState() –> onPause() –> onStop() –> onDestroy()

  • 有关onSaveInstanceState以及onRestoreInstanceState这两个方法我们都知道是用于Activity销毁和重建时数据的保存。

  • Back键或者是调用finish()方法去主动销毁Activity时,这时候系统会认为是我们不再需要该Activity,系统不会执行onSaveInstanceState
  • Home键直接将程序后台,这时候系统会执行onSaveInstanceState()这时候系统知道不是你不需要这个Activity只是后台了。
    此时我们唤醒应用,不会执行onRestoreInstanceState这个方法,因为我们后台再唤醒后该Activity并没有销毁重建,所以这时候就不会去调用onRestoreInstanceState
  • Home键会执行onSaveInstanceState,然后系统由于内存不足将进程杀死了,这时候系统就感觉自己做的不对,要给你恢复状态,当我们再次启动程序的时候就会执行onRestoreInstanceState这个方法来给我们恢复数据。
  • 在默认的Activity中,如果进行横竖屏切换的时候系统会销毁并且重新创建Activity,这时候系统就会执行onSaveInstanceState以及onRestoreInstanceState,因为这是系统把Activity给销毁了,系统要负责就执行这两个方法来给你保存和恢复数据。

15.三种不同的上下文

  • Activity.this
    Context的生命周期与Activity的生命周期相同。
    在创建对话框传递上下文的时候必须要传递Activit.this,因为对话框要指定挂载到哪个Activity上,对话框是挂载到Activity上,所以对话框弹出时Activity不会走onPause()方法。如果传递getApplicationContext()就会报错.
  • mContext.getApplicationContext()
    Context的生命周期与应用程序的进程相同,生命周期很长。
  • AndroidTestCase中getContext()
    Context是测试框架模拟出来的一个上下文环境。

一般的情况下传递Activity.thisService.this就能满足需求,但是如果有要求保持数据库的长时间打开等对生命周期有要求的情况下就要使用getApplicationContext
这样只要是应用程序的进程存活getApplicationContext就会一直存在.,考虑到内存泄露的问题,在没有特殊别要的情况下能用getApplicationContext就尽量用它,

16.Monkey测试

adb shell
monkey -p com.charon.test -v 500

17.Handler以及HandlerThread

  1. Handler
    `
    A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue.
    When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it – from that point on,
    it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

    There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

    Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long),
    and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received;
    the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler’s handleMessage(Message) method (requiring that you implement a subclass of Handler).

    When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed.
    The latter two allow you to implement timeouts, ticks, and other timing-based behavior.

    When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc)
    and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before,
    but from your new thread. The given Runnable or Message will then be scheduled in the Handler’s message queue and processed when appropriate.
    `

  2. HandlerThread
    Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.
    Handler是一个有Looper的线程,这个Looper可以用于创建Handler。也是就是该HandlerThread内部自己维护着一个消息队列以及Looper
    当我们使用以该Looper创建的Handler去执行handler.sendMessage(Message msg)或者handler.post(Runnable thread)时会将消息或者线程发送到HandlerThread这个线程中而不是主线程,
    消息队列也是由该线程自己执行而不会影响到主线程的执行,这样就防止了主UI线程能够及时响应用户的操作,防止了ANR错误。简单的说HandlerThread就是一个有Looper功能的Thread

示例代码:

HandlerThread handlerThread = new HandlerThread("Test");
handlerThread.start();
handler = new MyHandler(handlerThread.getLooper());

class MyHandler extends Handler {
    public MyHandler() {}
    public MyHandler(Looper looper) {
        super(looper);
    }
    @Override
    public void handleMessage(Message msg) {   
    //TODO 
    }
}

18.横竖屏切换

//强制横屏      
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);   

判断当前屏幕的横竖屏

if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 横屏
} else if (this.getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT) {
    // 竖屏
}

19.设置和取消全屏

protected void setFullscreen(boolean on) {
    Window win = getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    final int bits = WindowManager.LayoutParams.FLAG_FULLSCREEN;
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

20.毛玻璃效果

  1. 要想自定义一个毛玻璃效果必须在这个Activity中的onCreate方法中使用这一个代码

    // Have the system blur any windows behind this one.
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
        WindowManager.LayoutParams.FLAG_BLUR_BEHIND); 
  2. 但是发现这样仍然没有效果,这是因为APIDemo中对这个毛玻璃效果的Activity在项目清单文件中配置了一个主题,所以我们也要在我们的这个Activity中配置这个主题

    <activity
        android:name=".DragViewActivity"
        android:theme="@style/Theme.Transparent" >
    </activity> 
  3. 这是一个自定义的主题我们没有这个主题,要拷贝APIDemo中的这个主题到res-values-styles.xml中

    <style name="Theme.Transparent">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:colorForeground">#fff</item>
    </style> 
  4. 这里发现这个主题的名字有点奇怪来时Theme.Transparent说明这个主题是Theme这个主题的子类,所以也要把Theme这个主题拷贝进来
    xml
    <style name="Theme" parent="android:Theme"></style>

  • 邮箱 :charon.chui@gmail.com
  • Good Luck!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值