kernel的属性文件到android的java的读取(7 14)

来源:互联网 发布:java 小游戏源代码 编辑:程序博客网 时间:2024/06/06 03:58

1.实现的原因,kernel与android的上层的简单文件交互。
2.实现的原理,kernel写文件,android的app层读取。

kernel中实现属性文件:

static struct class *myusb_class = NULL;static dev_t myusb_devno;struct device *myusb_dev = NULL;static int usb_flag=0;static ssize_t usb_read(struct device *dev, struct device_attribute *attr, char *buf){    int ret = 0;    sprintf(buf, "%d\n",usb_flag);    ret = strlen(buf) + 1;    printk("usb %s on_off=%d\n",__func__,ret);    return ret;}static ssize_t usb_write(struct device *dev, struct device_attribute *attr, const char *buf, size_t size){    int on_off = simple_strtoul(buf, NULL, 10);    printk("usb %s on_off=%d\n",__func__,on_off);    usb_flag = on_off;    return size;}static DEVICE_ATTR(usb, 0664 , usb_read, usb_write);static int myusb_create_sysfs(void){    int err=0;    if( alloc_chrdev_region(&myusb_devno, 0, 1,"MYUSB") )    {        return -EAGAIN;    }    myusb_class = class_create(THIS_MODULE, "MYUSB");    myusb_dev = device_create(myusb_class, NULL, myusb_devno, NULL, "MYUSB");    if(NULL == myusb_dev)    {        return -EIO;    }    err = device_create_file(myusb_dev, &dev_attr_usb);    return err;}    if (src_detect){        usb_flag =1;        complete_all(&chip->src_det_raised);}    else{        usb_flag =0;        complete_all(&chip->src_det_lowered);}myusb_create_sysfs();  //create file 

java中读取:

/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */package com.android.server.job.controllers;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.net.Uri;import android.os.BatteryManager;import android.os.BatteryManagerInternal;import android.os.SystemClock;import android.os.UserHandle;import android.util.Slog;import android.provider.Settings;import android.media.AudioManager;import android.media.MediaPlayer;import android.media.Ringtone;import android.media.RingtoneManager;import com.android.internal.annotations.VisibleForTesting;import com.android.server.LocalServices;import com.android.server.job.JobSchedulerService;import com.android.server.job.StateChangedListener;import java.io.PrintWriter;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Timer;import java.util.TimerTask;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.io.PrintWriter;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.BufferedWriter;/** * Simple controller that tracks whether the phone is charging or not. The phone is considered to * be charging when it's been plugged in for more than two minutes, and the system has broadcast * ACTION_BATTERY_OK. */public class BatteryController extends StateController {    private static final String TAG = "JobScheduler.Batt";    private static final Object sCreationLock = new Object();    private static volatile BatteryController sController;    private List<JobStatus> mTrackedTasks = new ArrayList<JobStatus>();    private ChargingTracker mChargeTracker;    private static final String PATH_TAP_TO_WAKE = "/sys/class/MYUSB/MYUSB/usb";    boolean usb_flag = false;    public static BatteryController get(JobSchedulerService taskManagerService) {        synchronized (sCreationLock) {            if (sController == null) {                sController = new BatteryController(taskManagerService,                        taskManagerService.getContext(), taskManagerService.getLock());            }        }        return sController;    }    @VisibleForTesting    public ChargingTracker getTracker() {        return mChargeTracker;    }    @VisibleForTesting    public static BatteryController getForTesting(StateChangedListener stateChangedListener,                                           Context context) {        return new BatteryController(stateChangedListener, context, new Object());    }    private BatteryController(StateChangedListener stateChangedListener, Context context,            Object lock) {        super(stateChangedListener, context, lock);        mChargeTracker = new ChargingTracker();        mChargeTracker.startTracking();    }    @Override    public void maybeStartTrackingJobLocked(JobStatus taskStatus, JobStatus lastJob) {        final boolean isOnStablePower = mChargeTracker.isOnStablePower();        if (taskStatus.hasChargingConstraint()) {            mTrackedTasks.add(taskStatus);            taskStatus.setChargingConstraintSatisfied(isOnStablePower);        }    }    @Override    public void maybeStopTrackingJobLocked(JobStatus taskStatus, JobStatus incomingJob, boolean forUpdate) {        if (taskStatus.hasChargingConstraint()) {            mTrackedTasks.remove(taskStatus);        }    }    private void maybeReportNewChargingState() {        final boolean stablePower = mChargeTracker.isOnStablePower();        if (DEBUG) {            Slog.d(TAG, "maybeReportNewChargingState: " + stablePower);        }        boolean reportChange = false;        synchronized (mLock) {            for (JobStatus ts : mTrackedTasks) {                boolean previous = ts.setChargingConstraintSatisfied(stablePower);                if (previous != stablePower) {                    reportChange = true;                }            }        }        // Let the scheduler know that state has changed. This may or may not result in an        // execution.        if (reportChange) {            mStateChangedListener.onControllerStateChanged();        }        // Also tell the scheduler that any ready jobs should be flushed.        if (stablePower) {            mStateChangedListener.onRunJobNow(null);        }    }    public class ChargingTracker extends BroadcastReceiver {        /**         * Track whether we're "charging", where charging means that we're ready to commit to         * doing work.         */        private boolean mCharging;        /** Keep track of whether the battery is charged enough that we want to do work. */        private boolean mBatteryHealthy;        private boolean mPowerConnected;        public ChargingTracker() {        }        public void startTracking() {            IntentFilter filter = new IntentFilter();            // Battery health.            filter.addAction(Intent.ACTION_BATTERY_LOW);            filter.addAction(Intent.ACTION_BATTERY_OKAY);            // Charging/not charging.            filter.addAction(BatteryManager.ACTION_CHARGING);            filter.addAction(BatteryManager.ACTION_DISCHARGING);            filter.addAction(Intent.ACTION_POWER_CONNECTED);            filter.addAction(Intent.ACTION_POWER_DISCONNECTED);            mContext.registerReceiver(this, filter);            // Initialise tracker state.            BatteryManagerInternal batteryManagerInternal =                    LocalServices.getService(BatteryManagerInternal.class);            mBatteryHealthy = !batteryManagerInternal.getBatteryLevelLow();            mCharging = mPowerConnected = batteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);        }        boolean isOnStablePower() {            return mCharging && mBatteryHealthy;        }        @Override        public void onReceive(Context context, Intent intent) {            onReceiveInternal(intent);        }        @VisibleForTesting        public void onReceiveInternal(Intent intent) {            final String action = intent.getAction();            final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(),                Settings.Global.CHARGING_SOUNDS_ENABLED, 1) != 0;            //final String soundPath = "system/media/audio/notifications/Notice.ogg";            final String soundPath = Settings.Global.getString(mContext.getContentResolver(),                    Settings.Global.WIRELESS_CHARGING_STARTED_SOUND);/////////////////////////////////////        String value = "";            try {                FileReader fileReader = new FileReader(PATH_TAP_TO_WAKE);                BufferedReader br = new BufferedReader(fileReader);                value = br.readLine().substring(0, 1);                br.close();                fileReader.close();            } catch (FileNotFoundException e) {                Slog.e(TAG, "Failure in reading file", e);            } catch (IOException e) {                Slog.e(TAG, "Failure in reading file", e);            }        if("1".equals(value))        {            usb_flag=true;            try{            FileWriter fileWritter = new FileWriter(PATH_TAP_TO_WAKE);            BufferedWriter bw = new BufferedWriter(fileWritter);            bw.write("0");            bw.close();            }catch(Exception e){                Slog.e(TAG, "Failure in writing file", e);            }        }/////////////////////////////////////            if (Intent.ACTION_BATTERY_LOW.equals(action)) {                if (DEBUG) {                    Slog.d(TAG, "Battery life too low to do work. @ "                            + SystemClock.elapsedRealtime());                }                // If we get this action, the battery is discharging => it isn't plugged in so                // there's no work to cancel. We track this variable for the case where it is                // charging, but hasn't been for long enough to be healthy.                mBatteryHealthy = false;            } else if (Intent.ACTION_BATTERY_OKAY.equals(action)) {                if (DEBUG) {                    Slog.d(TAG, "Battery life healthy enough to do work. @ "                            + SystemClock.elapsedRealtime());                }                mBatteryHealthy = true;                maybeReportNewChargingState();            } else if (BatteryManager.ACTION_CHARGING.equals(action)) {                if (DEBUG) {                    Slog.d(TAG, "Received charging intent, fired @ "                            + SystemClock.elapsedRealtime());                }                mCharging = true;                if (!mPowerConnected) {                    mPowerConnected = true;                    if (enabled && soundPath != null) {                         Timer timer = new Timer();                        timer.schedule(new TimerTask(){                            public void run(){                                final Uri soundUri = Uri.parse("file://" + soundPath);                                if ((soundUri != null)&&usb_flag ) {                    usb_flag = false;                                    final Ringtone sfx = RingtoneManager.getRingtone(mContext, soundUri);                                    if (sfx != null) {                                        sfx.setStreamType(AudioManager.STREAM_SYSTEM);                                        sfx.play();                                    }                                }                                this.cancel();                            }                        },500);                    }                }                android.os.Vibrator vibrator = (android.os.Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);                if (vibrator != null) {                    vibrator.vibrate(500);                }                maybeReportNewChargingState();            } else if (BatteryManager.ACTION_DISCHARGING.equals(action)) {                if (DEBUG) {                    Slog.d(TAG, "Disconnected from power.");                }                mCharging = false;                mPowerConnected = false;                maybeReportNewChargingState();            } else if(Intent.ACTION_POWER_CONNECTED.equals(action)){                if (!mPowerConnected) {                    mPowerConnected = true;                    if (enabled && soundPath != null) {                        //bug:A6000-6060-xiajunjun-001 20170401 modify begin                        Timer timer = new Timer();                        timer.schedule(new TimerTask(){                            public void run(){                                final Uri soundUri = Uri.parse("file://" + soundPath);                                if( (soundUri != null)&&usb_flag) {                                    final Ringtone sfx = RingtoneManager.getRingtone(mContext, soundUri);                                    if (sfx != null) {                    usb_flag =false;                                        sfx.setStreamType(AudioManager.STREAM_SYSTEM);                                        sfx.play();                                    }                                }                                this.cancel();                            }                        },500);                    }                }                android.os.Vibrator vibrator = (android.os.Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);                if (vibrator != null) {                    vibrator.vibrate(500);                }            } else if (Intent.ACTION_POWER_DISCONNECTED.equals(action)) {//bug:A6090-4233-xiajunjun-001 20170323 modify                mPowerConnected = false;            }        }    }    @Override    public void dumpControllerStateLocked(PrintWriter pw, int filterUid) {        pw.print("Battery: stable power = ");        pw.println(mChargeTracker.isOnStablePower());        pw.print("Tracking ");        pw.print(mTrackedTasks.size());        pw.println(":");        for (int i = 0; i < mTrackedTasks.size(); i++) {            final JobStatus js = mTrackedTasks.get(i);            if (!js.shouldDump(filterUid)) {                continue;            }            pw.print("  #");            js.printUniqueId(pw);            pw.print(" from ");            UserHandle.formatUid(pw, js.getSourceUid());            pw.println();        }    }}

给属性文件的权限放开:

在init.rc中

chown system  /sys/class/MYUSB/MYUSB/usbchmod   777 /sys/class/MYUSB/MYUSB/usb