How can i start new Activity on Accelererometer (On Shake): when i shake my phone the app crashes
- the accelerometer run also in background
public class Shaker_Service extends Service implements SensorEventListener{
private static final String TAG = "MyService";
private SensorManager sensorManager;
AppPreferences appPrefs;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service CREATED", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service STOP", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service START", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
// assign directions
float x=event.values[0];
float y=event.values[1];
float z=event.values[2];
if (x>10){
startActivity(newIntent("com.examles.MESSAGE"));
}
}
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.examples"
android:versionCode="1"
android:versionName="1.0">
<activity android:name=".Message_Note"
android:label="#string/app_name"
>
<intent-filter>
<action android:name="com.examples.MESSAGE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".Shaker_Service" />
</application>
</manifest>
Message_Note.java :
public class Message_Note extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
}
}
image of error (LogCat)
https://mega.co.nz/#!SUpTAbAC!WC9y_Xlh5GEW9AY9_5WbpXwkYA4Xk-o9WgaXvN6jpLk
Try using:
Intent intent = new Intent(this, theActivityYouWantToStart.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
This is the correct way to start an Activity from inside a service.
Related
I m new on android
I want to start two services and one service sendbroadcast another will catch this broadcast but it is not working even if I register another service in this broadcasting
here is my code am I doing something wrong ?
Thanks advice.
public class MainActivity extends Activity {
Intent i;
Intent i2;
static final String LOG_TAG = "ServiceActivity";
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//Start service
i = new Intent(this, com.example.user.sensorservicetest.SimpleService.class);
i2= new Intent(this,com.example.user.sensorservicetest.AnotherService.class);
Log.d(LOG_TAG, "onCreate/startService");
}
#Override
public void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume/registering receiver");
//Register BroadcastReceiver to receive accelerometer data from service
startService(i);
startService(i2);
}
}
#Override
public void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause/unregistering receiver");
stopService(i);
stopService(i2);
}
#Override
protected void onStop() {
super.onStop();
Log.d(LOG_TAG, "onStop");
stopService(i);
stopService(i2);
}
}
SimpleService
public class SimpleService extends Service implements SensorEventListener {
private String reading;
private SensorManager mgr;
private List<Sensor> sensorList;
static final String LOG_TAG = "SimpleService";
Intent intent = new Intent("com.practice.SimpleService.MY_ACTION");
final static String MY_ACTION = "com.practice.SimpleService.MY_ACTION";
#Override
//public void onStartCommand() {
public void onCreate() {
Log.d(LOG_TAG, "onStartCommand");
mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mgr.getSensorList(Sensor.TYPE_ACCELEROMETER);
for (Sensor sensor : sensorList) {
mgr.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
Log.d(LOG_TAG, "onDestroy");
mgr.unregisterListener(this);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(LOG_TAG, "onSensorChanged");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < event.values.length; i++) {
builder.append(" [");
builder.append(i);
builder.append("] = ");
builder.append(event.values[i]);
builder.append("\n");
}
reading = builder.toString();
//Send back reading to Activity
intent.putExtra("measurement", reading);
sendBroadcast(intent);
}
}
AnotherService
public class AnotherService extends Service {
static final String TAG = "AnotherService";
private AnotherServiceReceiver anotherServiceReceiver = new AnotherServiceReceiver();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.practice.SimpleService.MY_ACTION");
registerReceiver(anotherServiceReceiver, intentFilter);
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
if (anotherServiceReceiver != null)
unregisterReceiver(anotherServiceReceiver);
super.onDestroy();
}
public static class AnotherServiceReceiver extends BroadcastReceiver {
static final String receiverTag = "AnotherServiceReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(receiverTag, "onReceive");
String measurement = intent.getStringExtra("measurement");
Log.d(receiverTag, "measurement - 2 : " + measurement);
}
}
}
Manifest
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="here is problem I think"
</intent-filter>
</receiver>
According #Evgeniy Mishustin answer (thanks to him)
Solution is adding service in manifest xml file now working each service communication
<service android:name=".SimpleService" ></service>
<service android:name=".AnotherService"></service>
<receiver android:name=".AnotherService$AnotherServiceReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.practice.SimpleService.MY_ACTION"></action>
</intent-filter>
</receiver>
</application>
In Android I am creating a Service, which will listen for sensor value change.
But my application keeps crashing whenever I open it. If I remove the Lines
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
It works fine
I have created the Service class as following:
public class CustomSensorService extends Service implements SensorEventListener{
static SensorManager sensorManager;
static Sensor mAccelerometer;
static Context mContext;
static final String LOG_TAG = "SimpleService";
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service Created",Toast.LENGTH_SHORT).show();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d( LOG_TAG, "onSensorChanged" );
Toast.makeText(mContext,"Heelooo" , Toast.LENGTH_SHORT).show();
stopSelf();
}
}
And my Activity as:
public class MainActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, CustomSensorService.class);
}
#Override
public void onResume(){
super.onResume();
startService(intent);
}
}
This is the Manifest
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.learnandroidservice.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".CustomSensorService"/>
</application>
Trace:
mContext is null - you need to initialise it before you pass it to Toast.makeText().
Service is a context so you can just call
Toast.makeText(this,"Heelooo" , Toast.LENGTH_SHORT).show();
It works when you remove the lines you mention because then the SensorListener is never registered, and onSensorChanged is never called.
In CustomSensorService class : Inside onSensorChanged() method: You used mContext variable value without initializing it.
Your code:
Toast.makeText(mContext,"Heelooo" , Toast.LENGTH_SHORT).show();
Changes to be done to resolve this issue:
Toast.makeText(this, "Heelooo", Toast.LENGTH_SHORT).show();
Due to the above reason you are getting NullPointerException while displaying toast.
I use AIDL interface IExtendedNetworkService to get USSD code. But application only work after reboot device. I tried bindservice after install app but it didn't work. So my problem is how way to bind service without reboot device . This is my code:
interface:
package com.android.internal.telephony;
interface IExtendedNetworkService {
void setMmiString(String number);
CharSequence getMmiRunningText();
CharSequence getUserMessage(CharSequence text);
void clearMmiString();
}
Service
public class CDUSSDService extends Service {
private String TAG = "THANG-NGUYEN";
private boolean mActive = false;
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_INSERT)) {
// activity wishes to listen to USSD returns, so activate this
mActive = true;
Log.d(TAG, "activate ussd listener");
} else if (intent.getAction().equals(Intent.ACTION_DELETE)) {
mActive = false;
Log.d(TAG, "deactivate ussd listener");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {
public void clearMmiString() throws RemoteException {
Log.d(TAG, "called clear");
}
public void setMmiString(String number) throws RemoteException {
Log.d(TAG, "setMmiString:" + number);
}
public CharSequence getMmiRunningText() throws RemoteException {
if (mActive == true) {
return null;
}
return "USSD Running";
}
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user message " + text);
if (mActive == false) {
// listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
// listener is active, so broadcast data and suppress it from
// default behavior
// build data to send with intent for activity, format URI as per
// RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(
getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(
getBaseContext().getString(R.string.uri_param_name),
text.toString()).build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
};
public void onCreate() {
Log.i(TAG, "called onCreate");
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "called onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "called onbind");
// the insert/delete intents will be fired by activity to
// activate/deactivate listener since service cannot be stopped
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
filter.addDataAuthority(
getBaseContext().getString(R.string.uri_authority), null);
filter.addDataPath(getBaseContext().getString(R.string.uri_path),
PatternMatcher.PATTERN_LITERAL);
registerReceiver(receiver, filter);
return mBinder;
}
}
MainActivity:
public class MainActivity extends Activity {
private Button btnCheckUSSD;
private Context mContext;
private IExtendedNetworkService mService;
private EditText inputUSSD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
btnCheckUSSD = (Button) findViewById(R.id.btn_check);
inputUSSD = (EditText) findViewById(R.id.input_ussd);
btnCheckUSSD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!inputUSSD.getText().toString().isEmpty()) {
Intent service = new Intent(
"com.android.ussd.IExtendedNetworkService");
bindService(service, mConnecton, Context.BIND_AUTO_CREATE);
startActivity(new Intent("android.intent.action.CALL", Uri
.parse("tel:" + inputUSSD.getText().toString()
+ Uri.encode("#"))));
}
}
});
}
ServiceConnection mConnecton = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
mService = IExtendedNetworkService.Stub
.asInterface((IBinder) iBinder);
}
};
protected void onDestroy() {
super.onDestroy();
Log.d("THANG-NGUYEN", "onDestroy");
unbindService(mConnecton);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.example.checkussdcode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="info.example.checkussdcode.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="info.example.checkussdcode.service.UssdCodeService"
android:process=":remote" >
<intent-filter>
<action android:name="com.android.ussd.IExtendedNetworkService" >
</action>
</intent-filter>
</service>
<receiver android:name="info.example.checkussdcode.RebootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
I have this Service class:
public class BluetoothService extends Service {
private static Activity mActivity;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(bluetoothReceiver, intentFilter);
}
#Override
public void onDestroy() {
if (bluetoothReceiver != null) {
this.unregisterReceiver(bluetoothReceiver);
}
}
#Override
public void onStart(Intent intent, int startid) {
//
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public static BroadcastReceiver bluetoothReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
TextView tvStatus = (TextView) mActivity.findViewById(R.id.tvtatus);
Messaging.appendMessage(tvStatus, Bluetooth.getDeviceState(state));
if (Bluetooth.isBluetoothEnabled()) {
Messaging.appendMessage(tvStatus, Bluetooth.showMessage());
}
}
}
};
}
And in my Activity class, I have this:
public class MainActivity extends Activity {
private TextView tvStatus;
private Intent intentBluetooth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView)findViewById(R.id.tvtatus);
intentBluetooth = new Intent(this, BluetoothService.class);
startService(intentBluetooth);
}
}
The BroadcastReceiver method (bluetoothReceiver) in the Service class is never called. I don't know why. If I have the IntentFilter and the BroadcastReceiver codes above all in an Activity, then it works - but not in a [separate] Service. I'm stumped.
My AndroidManifest.xml is:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.onegoal.androidexample"
android:versionCode="1"
android:versionName="1.0.0"
android:installLocation="auto"
android:hardwareAccelerated="true">
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth" android:required="false" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:debuggable="true" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BluetoothService">
</service>
</application>
</manifest>
I'm new to Android so what I'm doing may not be the best. Hope someone can help me.
maybe the fact that your receiver is static causing the problem.
BroadcastReceiver should never be static. it can cause lots of problems.
other really bad design problem with your code - holding reference to activity inside service, and using it to modify views is really wrong thing to do. it can cause easily to memory leek.
the right why to communicate between Service and Activity is by implement android's Messanger, or sending broadcasts between them via BroadcastReceiver.
if you'll listen to my advice - you won't be have to make your receiver static (I guess you've made it static only because you are using the mActivity static instance inside)
and I'm pretty sure it will solve your problem
you can read about Messanger here: http://developer.android.com/reference/android/os/Messenger.html
sure you'll find lots of usage examples in the net.
example of broadcasting updates to the activity from service:
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(bluetoothReceiver, intentFilter);
}
#Override
public void onDestroy() {
if (bluetoothReceiver != null) {
this.unregisterReceiver(bluetoothReceiver);
}
super.onDestroy();
}
public BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
updateUIWithNewState(state);
}
}
};
protected void updateUIWithNewState(int state) {
Intent intent = new Intent("serviceUpdateReceivedAction");
intent.putExtra("state", state);
sendBroadcast(intent);
}
}
and that's the activity:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mServiceUpdatesReceiver, new IntentFilter("serviceUpdateReceivedAction"));
}
#Override
protected void onPause() {
unregisterReceiver(mServiceUpdatesReceiver);
super.onPause();
}
private BroadcastReceiver mServiceUpdatesReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra("state", -1);
// do what ever you want in the UI according to the state
}
};
}
I want to have a sound when my application is installed. I tried this by using broadcastreciever in my application. In the broadcast reciever iam running a service to start media player. But iam not able to get into on recieve method of the broadcast reciever. but if i try to install another app iam getting the event. how to get the event in my app only.
My permissions in manifest file
<uses-permission android:name = "android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES"/>
<receiver android:name=".DemoReceiver" >
<intent-filter >
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<action android:name="android.intent.action.USER_PRESENT"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
and in the broadcast reciever
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DemoReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent bootintent) {
System.out.println("entered broadcast receiver");
if(bootintent.getAction() != null)
{
context.startService(new Intent(context, DemoService.class));
}
}
}
and the service is
public class DemoService extends Service {
MediaPlayer player;
private class LogTask extends TimerTask {
public void run() {
Log.i(LOGTAG, "scheduled");
}
}
private LogTask mLogTask;
#Override
public IBinder onBind(final Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.v("StartServiceAtBoot", "StartAtBootService Created");
player=MediaPlayer.create(this, R.raw.sirensound);
player.setLooping(false);
}
public void onStart(Intent intent, int flags, int startId) {
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
player.start();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v("StartServiceAtBoot", "StartAtBootService Destroyed");
}
}
If you want to execute any code from your app , it has to be already installed , so I think..you cannot receive broadcast from your app when your app is installed.
in my application I managed to create sound when a user shakes the device while my application is running....
public class SensorTest extends Activity implements SensorEventListener,
OnCompletionListener {
private SensorManager sensorManager;
private boolean color = false;
private long lastUpdate;
private MediaPlayer mMediaplayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
lastUpdate = System.currentTimeMillis();
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
if (color) {
} else {
try {
AssetFileDescriptor afd = getAssets().openFd(
"gavel_single.wav");
mMediaplayer = new MediaPlayer();
mMediaplayer.setDataSource(afd.getFileDescriptor(), afd
.getStartOffset(), afd.getLength());
afd.close();
mMediaplayer.prepare();
mMediaplayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
sensorManager.unregisterListener(this);
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mMediaplayer != null) {
mMediaplayer.release();
mMediaplayer = null;
}
}
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
mp.release();
}
}
You cannot do this on a standard Android platform, at least when distributing from a normal source (you might be able to do something by opening a web page with javascript and a link to the apk on your own server, but the users would have to enable "unkown sources" in their settings first)
You can, however, play a sound on first run. But an install only becomes a run if the user clicks "open" from the installer or launches it from the home screen, etc.