用Android stdio写一个程序,包含传感器及通知服务功能,写出Java代码和xml代码,及具体步骤,及具体步骤
时间: 2024-03-17 11:47:46 浏览: 174
好的,以下是具体步骤以及Java代码和xml代码。
步骤:
1. 创建一个Android Studio项目,选择Empty Activity模板。
2. 在AndroidManifest.xml文件中添加传感器和通知服务的权限声明。
```
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
```
3. 在activity_main.xml文件中添加一个TextView和一个Button。
```xml
<!-- activity_main.xml -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shake your phone to trigger a notification"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"/>
</LinearLayout>
```
4. 在MainActivity.java文件中实现传感器和通知服务的功能。
```java
// MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private long lastUpdateTime = 0;
private float lastX = 0, lastY = 0, lastZ = 0;
private static final float SHAKE_THRESHOLD = 800;
private boolean isShakeDetected = false;
private NotificationManager notificationManager;
private static final String CHANNEL_ID = "channel_id";
private static final String CHANNEL_NAME = "channel_name";
private static final String CHANNEL_DESC = "channel_desc";
private TextView textView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化传感器
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// 初始化通知服务
createNotificationChannel();
// 初始化UI组件
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopShakeDetection();
}
});
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
// 计算加速度变化
long currentTime = System.currentTimeMillis();
long timeDifference = currentTime - lastUpdateTime;
if (timeDifference > 0) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
float speed = Math.abs(x + y + z - lastX - lastY - lastZ) / timeDifference * 10000;
// 判断是否达到摇晃阈值
if (speed > SHAKE_THRESHOLD) {
if (!isShakeDetected) {
isShakeDetected = true;
showNotification();
}
} else {
isShakeDetected = false;
}
lastUpdateTime = currentTime;
lastX = x;
lastY = y;
lastZ = z;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private void showNotification() {
Toast.makeText(this, "Shake detected!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
android.app.PendingIntent pendingIntent = android.app.PendingIntent.getActivity(this, 0, intent, 0);
android.app.NotificationCompat.Builder builder = new android.app.NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Shake detected!")
.setContentText("Shake your phone again to trigger another notification.")
.setPriority(android.app.NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
notificationManager.notify(0, builder.build());
}
private void stopShakeDetection() {
isShakeDetected = false;
notificationManager.cancelAll();
}
}
```
这个程序会监听加速度传感器,在检测到摇晃时触发一个通知,并在用户点击通知时打开应用程序。用户也可以点击按钮停止摇晃检测并取消所有通知。
阅读全文