安卓JNI--小项目试验计时器

关于Android Studio 配置JNI的请看文章:
安卓学习–Android studio 1.5 JNI开发初探
安卓JNI–JNI底层C回调Java方法
关于Android Studio导入源码库请看文章:
导入maven源码库

app/build.gradle文件添加库支持

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:percent:23.1.1' //百分比库
    compile 'com.bigkoo:pickerview:1.0.3'        //TimePopupWindow库
}

布局XML(使用了百分比布局)


<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lianghuiyong.time.MainActivity">

    <android.support.percent.PercentRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_heightPercent = "50%">
        <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            app:layout_marginTopPercent = "35%"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="设置时间"
            android:id="@+id/button"
            android:textSize="25sp"
            android:layout_below="@+id/textview"
            android:layout_centerHorizontal="true"
            app:layout_marginTopPercent="15%" />
    android.support.percent.PercentRelativeLayout>

android.support.percent.PercentRelativeLayout>

MainActivity.java

package com.example.lianghuiyong.time;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePopupWindow;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("timecount-jni");
    }
    public native void timecount(int h,int m);

    private int hour = 0;
    private int min  = 0;
    private int sec  = 0;

    private Handler handler =null;
    private TextView textView = null;
    private Button button = null;
    private volatile boolean isstop = false;
    private volatile boolean isstar = true;
    private TimePopupWindow pickerView = null;
    private ExecutorService pool = null;

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

        textView = (TextView)findViewById(R.id.textview);
        button = (Button)findViewById(R.id.button);

        this.Config_PickerView();
        this.HandlerGetData();//handler 更新UI

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickerView.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            }
        });
    }


    /*
    * 配置pickerView
    * */
    private void Config_PickerView(){
        pool = Executors.newSingleThreadExecutor();  //采用线程池单一线程方式
        pickerView = new TimePopupWindow(MainActivity.this, TimePopupWindow.Type.HOURS_MINS);
        pickerView.setTime(new Date(2015 - 1900, 12, 10, 0, 0));//设置时间
        pickerView.setCyclic(true); //循环滚动

        //监听pickerView按下确定按钮
        pickerView.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                IfThreadSetStop();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                final int set_hour = calendar.get(Calendar.HOUR_OF_DAY);
                final int set_min = calendar.get(Calendar.MINUTE);


                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("lhy", "按下确定调用JNI:set_hour = " + set_hour + "; set_min = " + set_min);
                        timecount(set_hour, set_min);
                    }
                });
            }
        });
    }

    //判断线程是不是第一个,如果不是,则把isstop置为false,JNI回调时会结束无限循环
    private void IfThreadSetStop(){
        if (!isstar)
            isstop = true;
        isstar = false;
    }

    /*
    * 通过handle获取msg里的值
    * */
    private void HandlerGetData(){
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        Bundle bundle = msg.getData();
                        hour = bundle.getInt("hour");
                        min  = bundle.getInt("min");
                        sec  = bundle.getInt("sec");
                        textView.setText(String.format("%02d", hour) + ":" +String.format("%02d", min)  + ":" + String.format("%02d", sec));
                        break;
                }
                super.handleMessage(msg);
            }
        };
        textView.setText(String.format("%02d", hour) + ":" + String.format("%02d", min) + ":" + String.format("%02d", sec));
    }

    /*
    *JNI回调用来传递时间
    * */
    private void MsgSetData(int h,int m,int s){
        Message msg = new Message();
        msg.what = 1;
        Bundle bundle = new Bundle();
        bundle.putInt("hour",h);
        bundle.putInt("min",m);
        bundle.putInt("sec",s);
        msg.setData(bundle);
        handler.sendMessage(msg);
        Log.d("lhy", "JNI sendMessage OK!--" + h + ":" + m + ":" + s);
    }
}

timecount-jni.c

#include 
#include 

JNIEXPORT void JNICALL
Java_com_example_lianghuiyong_time_MainActivity_timecount(JNIEnv *env, jobject instance, jint h,
                                                          jint m) {

    // TODO
    jclass mainactivity = (*env)->FindClass(env ,"com/example/lianghuiyong/time/MainActivity");
    jmethodID MsgSetData = (*env)->GetMethodID(env,mainactivity,"MsgSetData","(III)V");

    jfieldID isstopID = (*env)->GetFieldID(env,mainactivity,"isstop","Z");

    volatile jboolean  isstop = NULL;
    isstop= (*env)->GetBooleanField(env,instance,isstopID);

    int s=0;    //初始化秒为0
    //回调Java的MsgSetData方法更新UI
    (*env)->CallVoidMethod(env,instance,MsgSetData,h,m,s);

    while ((!isstop)&&( h>=0 && m>=0 && s>=0)){
        if(  s>0 ){
            --s;
        } else if( m>0 && s==0 ){
            --m;
            s = 59;
        } else if(h>0 && m==0 && s==0 ){
            --h;
            m = 59;
            s = 59;
        }

        sleep(1);

        //回调Java的MsgSetData方法更新UI
        (*env)->CallVoidMethod(env,instance,MsgSetData,h,m,s);
        isstop = (*env)->GetBooleanField(env,instance,isstopID);
    }

    //结束时重置Java属性isstop为false
    (*env)->SetBooleanField(env,instance,isstopID,JNI_FALSE);

    //回收资源
    (*env)->DeleteGlobalRef(env,instance);
}

安卓JNI--小项目试验计时器_第1张图片

你可能感兴趣的:(安卓)