注意:CloseActivity.java为空
是否有机会关闭通知中的手电筒(或应用程序)?
public class MainActivity extends AppCompatActivity {
String content = "Flashlight is on";
private Camera cam1;
Camera.Parameters params;
private Camera.Parameters parameter;
private boolean isOn;
private boolean checkAndRequestPermissions() {
int permissionCAMERA = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionCAMERA != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1905;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!checkAndRequestPermissions()) {
return;
}
else {
cam1 = Camera.open();
parameter = this.cam1.getParameters();
}
}
public void sendNotification(View view){
final Button btn =(Button) findViewById(R.id.button);
if (isOn){
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cam1.setParameters(params);
cam1.stopPreview();
isOn=false;
btn.setBackgroundResource(R.drawable.off);
}
else {
params=cam1.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam1.setParameters(params);
cam1.startPreview();
isOn=true;
btn.setBackgroundResource(R.drawable.on);
switch(view.getId()){
case R.id.button:
addNotification();
break;
}
}
}
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notif)
.setContentTitle("FlasLight")
.setContentText("Tap To Close");
Intent notificationIntent = new Intent(this, CloseActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}