Java 在手机睡眠时使用Android加速计和短信

Java 在手机睡眠时使用Android加速计和短信,java,android,sms,accelerometer,Java,Android,Sms,Accelerometer,我有一个应用程序,记录加速度计数据,并在通过treshhold时发送短信。当手机处于唤醒状态时,它可以正常工作。我需要做什么?这是在手机处于锁定/睡眠状态时也要做同样的操作: 我有两个活动SendSMSActivity.java: package com.example.sendsms; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; imp

我有一个应用程序,记录加速度计数据,并在通过treshhold时发送短信。当手机处于唤醒状态时,它可以正常工作。我需要做什么?这是在手机处于锁定/睡眠状态时也要做同样的操作:

我有两个活动SendSMSActivity.java:

package com.example.sendsms;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.FilterQueryProvider;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class SendSMSActivity extends Activity implements SensorEventListener {
    SendSMS mSender = new SendSMS();
    private SensorManager senSensorManager;
    private Sensor senAccelerometer;
    private long lastUpdate;
    private float last_x, last_y, last_z;
  //Contacts variable
    AutoCompleteTextView emailText;
    ContentResolver cr;
    SimpleCursorAdapter emailAdapter;


    protected void onResume() {
        super.onResume();
        senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        senSensorManager.unregisterListener(this);
    }

        @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //To change body of implemented methods use File | Settings | File Templates.
        Sensor mySensor = sensorEvent.sensor;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = sensorEvent.values[0];
            float y = sensorEvent.values[1];
            float z = sensorEvent.values[2];

            long curTime = System.currentTimeMillis();
            // only allow one update every 100ms.
            if ((curTime - lastUpdate) > 100) {
                long diffTime = (curTime - lastUpdate);
                lastUpdate = curTime;

                float speed = Math.abs(x+y+z - last_x - last_y - last_z)/ diffTime * 10000;
                TextView threshText = (TextView)findViewById(R.id.thresh);

                if (speed > Float.parseFloat(threshText.getText().toString())) {
                    Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
                      Toast.makeText(this, "shake detected w/ speed: " + speed, Toast.LENGTH_SHORT).show();
                     TextView resultText = (TextView)findViewById(R.id.xacc);
                         resultText.setText("shake detected w/ speed: " + speed);
                    sendit2();
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }
    }

        @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // can be safely ignored for this demo
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         // Get an instance of the SensorManager
        senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
        //Contacts
        cr = getContentResolver();
        emailText = (AutoCompleteTextView) findViewById(R.id.mobileNo);
        String[] fromCols = {
                ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA,
        };
        int[] toViewIds = { R.id.list_name, R.id.list_email };
        emailAdapter = new SimpleCursorAdapter(this, R.layout.email_and_name, getNamesAndEmails(null), fromCols, toViewIds);

        // Important 1: You have to provide a way of making the chosen choice look presentable.
        // emailAdapter.setStringConversionColumn(1); // 1=DISPLAY_NAME, 2=Email
        emailAdapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
            @Override
            public CharSequence convertToString(Cursor cursor) {
                return String.format("%s <%s>", cursor.getString(1).trim(), cursor.getString(2).trim());
            }
        });

        // Important 2: You have to provide a query containing the values on demand
        emailAdapter.setFilterQueryProvider(new FilterQueryProvider() {

            public Cursor runQuery(CharSequence constraint) {
                String partialItemName = null;
                if (constraint != null) {
                    partialItemName = constraint.toString();
                }
                return getNamesAndEmails(partialItemName);
            }
        });

        emailText.setAdapter(emailAdapter);
    }
//Contacts
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

    final static String[] PROJECTION = new String[] {
            ContactsContract.RawContacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.DATA,
            ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
            ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
    };

    /** Get the contacts that have email addresses matching "partialName".
     * @author Modified from code obtained from
     * http://stackoverflow.com/questions/5205999/android-get-a-cursor-only-with-contacts-that-have-an-email-listed-android-2-0
     * @return
     */
    Cursor getNamesAndEmails(String partialName) {
        // Look for partialName either in display name (person name) or in email
        final String filter =
                ContactsContract.Contacts.DISPLAY_NAME + " LIKE '%" + partialName + "%'" +
                        " OR " +
                        ContactsContract.CommonDataKinds.Phone.DATA + " LIKE '%" + partialName + "%'";
        // If display name contains "@" (maybe it's null so Contacts provides email here),
        // order by email, else order by display name.
        final String order = "CASE WHEN "
                + ContactsContract.Contacts.DISPLAY_NAME
                + " NOT LIKE '%@%' THEN 1 ELSE 2 END, "
                + ContactsContract.Contacts.DISPLAY_NAME
                + ", "
                + ContactsContract.CommonDataKinds.Phone.DATA
                + " COLLATE NOCASE";
        // Now make a Cursor containing the contacts that now match partialName as per "filter".
        return cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, filter, null, order);
    }


    public void sendit(View v) {
        TextView mobileNum = (TextView)findViewById(R.id.mobileNo);
        boolean success = mSender.sendSMSMessage(mobileNum.getText().toString(),
            // This is standard lorem-ipsum text, do not bother
            // trying to wrap it, there's about 500 characters...
            "Movement detected."
            );
        Toast.makeText(this, "Message sent " + (
            success ? "successfully" : "unsuccessfully"), 
            Toast.LENGTH_SHORT).show();
         TextView resultText = (TextView)findViewById(R.id.xacc);
            resultText.setText("Message Sent");
    }
    public void sendit2() {
        TextView mobileNum = (TextView)findViewById(R.id.mobileNo);
        boolean success = mSender.sendSMSMessage(mobileNum.getText().toString(),
            // This is standard lorem-ipsum text, do not bother
            // trying to wrap it, there's about 500 characters...
            "Movement detected."
            );
        Toast.makeText(this, "Message sent " + (
            success ? "successfully" : "unsuccessfully"), 
            Toast.LENGTH_SHORT).show();
         TextView resultText = (TextView)findViewById(R.id.xacc);
            resultText.setText("Message Sent");
    }

}
package com.example.sendsms;
导入android.app.Activity;
导入android.content.ContentResolver;
导入android.content.Context;
导入android.database.Cursor;
导入android.hardware.Sensor;
导入android.hardware.SensorEvent;
导入android.hardware.SensorEventListener;
导入android.hardware.SensorManager;
导入android.os.Bundle;
导入android.provider.contacts合同;
导入android.view.Menu;
导入android.view.view;
导入android.widget.AutoCompleteTextView;
导入android.widget.FilterQueryProvider;
导入android.widget.SimpleCursorAdapter;
导入android.widget.TextView;
导入android.widget.Toast;
公共类SendsMasActivity扩展活动实现SensorEventListener{
SendSMS mSender=新的SendSMS();
私人传感器管理器传感器管理器;
专用传感器;
私人长期更新;
私人浮动last_x,last_y,last_z;
//接触变量
自动完成文本查看电子邮件文本;
内容分解器cr;
SimpleCursorAdapter电子邮件适配器;
受保护的void onResume(){
super.onResume();
senSensorManager.registerListener(此、senAccelerator、SensorManager.SENSOR\u延迟\u正常);
}
受保护的void onPause(){
super.onPause();
senSensorManager.unregisterListener(此);
}
@凌驾
传感器更改时的公共无效(传感器事件传感器事件){
//要更改已实现方法的主体,请使用文件|设置|文件模板。
传感器mySensor=sensorEvent.Sensor;
if(mySensor.getType()==Sensor.TYPE\u加速计){
浮点x=传感器事件。值[0];
浮动y=传感器事件值[1];
浮动z=传感器事件值[2];
long curTime=System.currentTimeMillis();
//仅允许每100ms更新一次。
如果((curTime-lastUpdate)>100){
long diffTime=(curTime-lastUpdate);
lastUpdate=curTime;
浮动速度=Math.abs(x+y+z-last_x-last_y-last_z)/diffTime*10000;
TextView threshText=(TextView)findViewById(R.id.thresh);
if(speed>Float.parseFloat(threshText.getText().toString())){
Toast.makeText(这是“检测到的震动w/speed:+速度,Toast.LENGTH_SHORT.show”);
Toast.makeText(这是“检测到的震动w/speed:+速度,Toast.LENGTH_SHORT.show”);
TextView resultText=(TextView)findViewById(R.id.xacc);
resultText.setText(“检测到震动,速度:+速度”);
sendit2();
}
最后的x=x;
最后的y=y;
last_z=z;
}
}
}
@凌驾
精度更改时的公共无效(传感器,int精度){
//可以安全地忽略此演示
}
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取SensorManager的实例
senSensorManager=(SensorManager)getSystemService(Context.SENSOR\u SERVICE);
SenAccelerator=senSensorManager.getDefaultSensor(传感器类型\加速计);
senSensorManager.registerListener(此、senAccelerator、SensorManager.SENSOR\u延迟\u正常);
//接触
cr=getContentResolver();
emailText=(AutoCompleteTextView)findViewById(R.id.mobileNo);
字符串[]fromCols={
Contacts contract.CommonDataTypes.StructuredName.GIVEN_NAME,
Contacts contract.Contacts.DISPLAY\u NAME,
Contacts contract.CommonDataTypes.Phone.DATA,
};
int[]toViewIds={R.id.list\u name,R.id.list\u email};
emailAdapter=new SimpleCursorAdapter(this,R.layout.email_和_name,getNamesAndEmails(null),fromCols,toViewIds);
//重要提示1:您必须提供一种方法,使所选的选择看起来像样。
//emailAdapter.setStringConversionColumn(1);//1=显示\u名称,2=电子邮件
emailAdapter.setCursorToStringConverter(新的SimpleCursorAdapter.CursorToStringConverter(){
@凌驾
公共字符序列convertToString(游标){
返回String.format(“%s”,cursor.getString(1.trim(),cursor.getString(2.trim());
}
});
//要点2:您必须提供一个包含所需值的查询
emailAdapter.setFilterQueryProvider(新的FilterQueryProvider(){
公共游标运行查询(CharSequence约束){
字符串partialItemName=null;
if(约束!=null){
partialItemName=constraint.toString();
}
返回getNamesAndEmails(partialItemName);
}
});
setAdapter(emailAdapter);
}
//接触
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
最终静态字符串[]投影=新字符串[]{
Contacts contract.raw contacts.\u ID,
Contacts contract.Contacts.DISPLAY\u NAME,
Contacts contract.CommonDataTypes.Phone.DATA,
Contacts contract.CommonDataTypes.StructuredName.GIVEN_NAME,
Contacts contract.CommonDataTypes.StructuredName.FAMILY\u NAME,
};
/**获取电子邮件地址与“partialName”匹配的联系人。
*@author已从从获取的代码中修改
package com.example.sendsms;

import java.util.ArrayList;

import android.telephony.SmsManager;
import android.util.Log;

/** The code for dealing with the SMS manager; 
 * called from the GUI code.
 */
public class SendSMS {
    static String TAG = "SendSMS";
    SmsManager mSMSManager = null;
    /* The list of message parts our messge
     * gets broken up into by SmsManger */
    ArrayList<String> mFragmentList = null;
    /* Service Center - not used */
    String mServiceCentreAddr = null;

    SendSMS() {
        mSMSManager = SmsManager.getDefault();
    }

    /* Called from the GUI to send one message to one destination */
    public boolean sendSMSMessage(
            String aDestinationAddress,
            String aMessageText) {

        if (mSMSManager == null) {
            return (false);
        }

        mFragmentList = mSMSManager.divideMessage(aMessageText);
        int fragmentCount = mFragmentList.size();
        if (fragmentCount > 1) {
            Log.d(TAG, "Sending " + fragmentCount + " parts");
            mSMSManager.sendMultipartTextMessage(aDestinationAddress, 
                    mServiceCentreAddr,
                    mFragmentList, null, null);
        } else {
            Log.d(TAG, "Sendine one part");
            mSMSManager.sendTextMessage(aDestinationAddress, 
                    mServiceCentreAddr,
                    aMessageText, null, null);
        }

        return true;
    }
}