I can not stop (kill) my intent service. This is how I started my service:
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
And this is my intent service :
public class UsbService extends Service {
public static final String ACTION_USB_READY = "pl.gps.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "pl.gps.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "pl..gps.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "pl.gps.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "pl.gps.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "pl.gps.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "pl.gps.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "pl.gps.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 1;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private IBinder binder = new UsbBinder();
private Context context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
String date = "";
public static boolean check(String s) {
if (s.contains("$GNRMC")) {
return true;
}
return false;
}
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null) {
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
connection = usbManager.openDevice(device);
serialPortConnected = true;
new ConnectionThread().run();
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
serialPortConnected = false;
serialPort.close();
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
#Override
public void onCreate() {
this.context = this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
HashMap<String, UsbDevice> usbDevices1 = new HashMap<String, UsbDevice>();
usbDevices1.clear();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
if (deviceVID == 1659 && devicePID == 8963) {
// There is a device connected to our Android device. Try to open it as a Serial Port.
requestUserPermission();
keep = false;
if (!keep)
break;
}
}
if (!keep) {
// There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
public void unReg(){
// if(usbReceiver != null)
// unregisterReceiver(usbReceiver);
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
private void requestUserPermission() {
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort != null && serialPort.open()) {
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
I try di this :
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
if (timer != null)
timer.cancel();
Intent intent = new Intent(MainMenu.this, UsbService.class);
stopService(intent);
But my intent service steal is working. I try did whis when I destroyed my activity in which I created this service but when this activity is destroyed in logs I see that all the time this intent service is steel working
Related
Let's pretend that I have a flutter application and I have a Foreground Service that has a worker thread and keeps sending me updates about user's location, this is the service's code which returns a random integer numbers for now :
Android Service code
public class LocationUpdatesService extends Service {
static final int NOTIFICATION_ID = 100;
static final String NOTIFICATION = "com.example.fitness_app";
NotificationManagerCompat m_notificationManager;
private Intent m_broadcastInent;
private final String TAG = this.getClass().getSimpleName();
private AtomicBoolean working = new AtomicBoolean(true);
private int steps = 0;
private Runnable runnable = new Runnable() {
#Override
public void run() {
while(working.get()) {
steps++;
m_notificationManager.notify(NOTIFICATION_ID,
createNotification("Steps Counter" + steps ,
R.drawable.common_full_open_on_phone, 1));
m_broadcastInent.putExtra("steps", steps);
sendBroadcast(m_broadcastInent);
}
}
};
#Override
public void onCreate() {
m_broadcastInent = new Intent(NOTIFICATION);
m_notificationManager = NotificationManagerCompat.from(this);
createNotificationChannel();
startForeground(NOTIFICATION_ID, createNotification("Steps Counter" ,
R.drawable.common_full_open_on_phone, 0));
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(runnable).start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
working.set(false);
m_notificationManager.cancel(NOTIFICATION_ID);
super.onDestroy();
}
private Notification createNotification(String title, int icon, int steps) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID));
builder.setNumber(steps);
builder.setSmallIcon(icon);
builder.setContentTitle(title);
builder.setOnlyAlertOnce(true);
return builder.build();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID);
String description =
getString(R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_DESCRIPTION);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel =
new NotificationChannel(getString(
R.string.BACKGROUND_SERVICE_NOTIFICATION_CHANNEL_ID), name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
In MainActivity.java I am recieving broadcasts from the service and I should send them to the flutter side:
MainActivity
public class MainActivity extends FlutterActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String ONE_TIME_BACKGROUND_METHOD_CHANNEL = "fitness_app/method_one_time_service";
private static final String EVENTS_STREAM_CHANNEL = "fitness_app/event_one_time_service";
private Intent m_serviceIntent;
private MethodChannel m_methodChannel;
private EventChannel m_eventchannel;
private EventChannel.EventSink m_stepsStreamSink;
private EventChannel.StreamHandler m_eventCallHandler;
private MethodChannel.Result m_result;
private EventChannel.EventSink m_eventSink;
private BroadcastReceiver m_serviceBroadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Log.d(TAG, "milliseconds " + intent.getIntExtra("steps", 0));
Bundle bundle = intent.getExtras();
if (bundle != null) {
int steps = bundle.getInt("steps");
/////////////////////////////////////////
/////////////////////////////////////////
// I need Here To add Data To the stream
/////////////////////////////////////////
/////////////////////////////////////////
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
m_serviceIntent = new Intent(this, LocationUpdatesService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, m_serviceIntent, 0);
m_methodChannel = new MethodChannel(getFlutterView(), ONE_TIME_BACKGROUND_METHOD_CHANNEL);
m_methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("START_STEPS_COUNTER")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(m_serviceIntent);
} else {
startService(m_serviceIntent);
}
} else {
stopService(m_serviceIntent);
}
}
});
m_eventchannel = new EventChannel(getFlutterView(), EVENTS_STREAM_CHANNEL);
m_eventCallHandler = new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
m_eventSink = eventSink;
}
#Override
public void onCancel(Object o) {
}
};
m_eventchannel.setStreamHandler(m_eventCallHandler);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(m_serviceBroadcastReciever, new IntentFilter(LocationUpdatesService.NOTIFICATION));
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Flutter dart code
void start() async {
try {
await _methodChannel.invokeMethod(PlatformMethods.STEPS_COUNTER_START);
Stream<int> stream = _eventChannel.receiveBroadcastStream();
} on PlatformException catch (e) {
print(
" Faild to run native service with thrown exception : ${e.toString()}");
}
Everything here works fine. I can Trigger the service using the Methodchannel, I receive the data from the service using the BroadCastREciever.
All I need to do is to return a stream from the native code using EventChannel.
Create a class that extends BroadcastReceiver and pass a EventChannel.EventSink.
class SinkBroadcastReceiver(private val sink: EventChannel.EventSink) {
override fun onReceive(context: Context, intent: Intent) {
val bundle = intent.getExtras()
if (bundle != null) {
val steps = bundle.getInt("steps")
sink.success(steps)
}
}
}
Then, instead od create the BroadcastReceiver in the declaration you can create it in the onListen and call registerReceiver there:
m_eventCallHandler = new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
SinkBroadcastReceiver receiver = new SinkBroadcastReceiver(eventSink);
registerReceiver(receiver, new IntentFilter(LocationUpdatesService.NOTIFICATION));
// TODO : Save receiver in a list to call unregisterReceiver later
}
#Override
public void onCancel(Object o) {
}
};
You may need to track all the receivers in a list because you may need to unregister when the activity stops. Also when you stop the service you may need to traverse the list of registered BroadcastReceiver to unregister all the instances.
This way you may also have more than one listener on the dart code for the same event.
I tried to use new AudioPlaybackCapture method to record some media in an android 10 device. But unfortunately my code which uses this API does not seem to be working well.
Here I used an activity which starts a separate service for media recording. That service is registered to a broadcast receiver to start and stop recordings. And the broadcast intents are fired using my main activity via button clicks (start, stop)
No exceptions are printed. Also the file is created at the desired location. But with no content (0bytes). All the required manifest and runtime permissions are given. What i'm doing wrong here.
Here is my service
public class MediaCaptureService extends Service {
public static final String ACTION_ALL = "ALL";
public static final String ACTION_START = "ACTION_START";
public static final String ACTION_STOP = "ACTION_STOP";
public static final String EXTRA_RESULT_CODE = "EXTRA_RESULT_CODE";
public static final String EXTRA_ACTION_NAME = "ACTION_NAME";
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
NotificationCompat.Builder _notificationBuilder;
NotificationManager _notificationManager;
private String NOTIFICATION_CHANNEL_ID = "ChannelId";
private String NOTIFICATION_CHANNEL_NAME = "Channel";
private String NOTIFICATION_CHANNEL_DESC = "ChannelDescription";
private int NOTIFICATION_ID = 1000;
private static final String ONGING_NOTIFICATION_TICKER = "RecorderApp";
int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format
AudioRecord _recorder;
private boolean isRecording = false;
private MediaProjectionManager _mediaProjectionManager;
private MediaProjection _mediaProjection;
Intent _callingIntent;
public MediaCaptureService() {
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Call Start foreground with notification
Intent notificationIntent = new Intent(this, MediaCaptureService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
_notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Starting Service")
.setContentText("Starting monitoring service")
.setTicker(ONGING_NOTIFICATION_TICKER)
.setContentIntent(pendingIntent);
Notification notification = _notificationBuilder.build();
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
_notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
_notificationManager.createNotificationChannel(channel);
startForeground(NOTIFICATION_ID, notification);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
_mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
_callingIntent = intent;
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_ALL);
registerReceiver(_actionReceiver, filter);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startRecording(Intent intent) {
//final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
_mediaProjection = _mediaProjectionManager.getMediaProjection(-1, intent);
startRecording(_mediaProjection);
}
#TargetApi(29)
private void startRecording(MediaProjection mediaProjection ) {
AudioPlaybackCaptureConfiguration config =
new AudioPlaybackCaptureConfiguration.Builder(mediaProjection)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.build();
AudioFormat audioFormat = new AudioFormat.Builder()
.setEncoding(RECORDER_AUDIO_ENCODING)
.setSampleRate(RECORDER_SAMPLERATE)
.setChannelMask(RECORDER_CHANNELS)
.build();
_recorder = new AudioRecord.Builder()
// .setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(audioFormat)
.setBufferSizeInBytes(BufferElements2Rec * BytesPerElement)
.setAudioPlaybackCaptureConfig(config)
.build();
_recorder.startRecording();
writeAudioDataToFile();
}
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
Log.i(MainActivity.LOG_PREFIX, "Recording started. Computing output file name");
File sampleDir = new File(getExternalFilesDir(null), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String fileName = "Record-" + new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss").format(new Date()) + ".pcm";
String filePath = sampleDir.getAbsolutePath() + "/" + fileName;
//String filePath = "/sdcard/voice8K16bitmono.pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
_recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.i(MainActivity.LOG_PREFIX, String.format("Recording finished. File saved to '%s'", filePath));
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void stopRecording() {
// stops the recording activity
if (null != _recorder) {
isRecording = false;
_recorder.stop();
_recorder.release();
_recorder = null;
}
_mediaProjection.stop();
stopSelf();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(_actionReceiver);
}
BroadcastReceiver _actionReceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_ALL)) {
String actionName = intent.getStringExtra(EXTRA_ACTION_NAME);
if (actionName != null && !actionName.isEmpty()) {
if (actionName.equalsIgnoreCase(ACTION_START)) {
startRecording(_callingIntent);
} else if (actionName.equalsIgnoreCase(ACTION_STOP)){
stopRecording();
}
}
}
}
};
And here is an extract from the main activity where the service and start / stop actions are started.
public class MainActivity extends AppCompatActivity {
public static final String LOG_PREFIX = "CALL_FUNCTION_TEST";
private static final int ALL_PERMISSIONS_PERMISSION_CODE = 1000;
private static final int CREATE_SCREEN_CAPTURE = 1001;
Button _btnInitCapture;
Button _btnStartCapture;
Button _btnStopCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnGetOkPermissions = findViewById(R.id.btnGetOkPermissions);
_btnGetOkPermissions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkOkPermissions();
}
});
_btnInitCapture = findViewById(R.id.btnInitCapture);
_btnInitCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initAudioCapture();
}
});
_btnStartCapture = findViewById(R.id.btnStartCapture);
_btnStartCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startRecording();
}
});
_btnStopCapture = findViewById(R.id.btnStopAudioCapture);
_btnStopCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopRecording();
}
});
}
...
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAudioCapture() {
_manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = _manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
private void stopRecording() {
Intent broadCastIntent = new Intent();
broadCastIntent.setAction(MediaCaptureService.ACTION_ALL);
broadCastIntent.putExtra(MediaCaptureService.EXTRA_ACTION_NAME, MediaCaptureService.ACTION_STOP);
this.sendBroadcast(broadCastIntent);
}
private void startRecording() {
Intent broadCastIntent = new Intent();
broadCastIntent.setAction(MediaCaptureService.ACTION_ALL);
broadCastIntent.putExtra(MediaCaptureService.EXTRA_ACTION_NAME, MediaCaptureService.ACTION_START);
this.sendBroadcast(broadCastIntent);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (CREATE_SCREEN_CAPTURE == requestCode) {
if (resultCode == RESULT_OK) {
Intent i = new Intent(this, MediaCaptureService.class);
i.setAction(MediaCaptureService.ACTION_START);
i.putExtra(MediaCaptureService.EXTRA_RESULT_CODE, resultCode);
i.putExtras(intent);
this.startService(i);
} else {
// user did not grant permissions
}
}
}
}
Well, nothing sets isRecording true. Also, you're doing your recording in a blocking method, but you're on the UI thread, which ought to cause your interface to freeze as soon as you start recording.
I wanted my Android to communicate with an Arduino using an USB host. I've tried many references but can't seem to send any char to my Arduino. I can detect my Arduino but sending char or string to it is frustrating. Here are my codes:
MainActivity.java
public class MainActivity extends AppCompatActivity {
UsbDevice device=null;
UsbManager manager=null;
PendingIntent mPermissionIntent;
UsbInterface intf;
UsbEndpoint endpoint;
UsbDeviceConnection connection;
Button find;
Button send;
TextView hello;
UsbManager mUsbManager;
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find = (Button) findViewById(R.id.Find);
send = (Button) findViewById(R.id.Send);
hello = (TextView) findViewById(R.id.hello);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hello.setText("");
checkInfo();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(device!=null) {
intf = device.getInterface(0);
endpoint = intf.getEndpoint(0);
connection = mUsbManager.openDevice(device);
hello.setText("Kirim");
String kirim = "a";
bytes = kirim.getBytes();
connection.claimInterface(intf, forceClaim);
connection.bulkTransfer(endpoint, bytes, bytes.length, 0);
}
else{
Toast.makeText(MainActivity.this,"Device ==
null",Toast.LENGTH_SHORT);
}
}
});
private void checkInfo(){
manager=(UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this,0,new
Intent(ACTION_USB_PERMISSION),0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver,filter);
HashMap<String,UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String i="";
int j=0;
while(deviceIterator.hasNext()){
device = deviceIterator.next();
manager.requestPermission(device,mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
j++;
}
hello.setText(i);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " +
device);
}
}
}
}
};
}
I iterate using a find button and send using a send button. The iteration went just fine, but the sending didn't work. I needed to send just a character to the Arduino. My phone supports OTG and had been tested using other serial communication application to send char to Arduino and it works just fine.
Thanks in advance
using the usb serial lib in releases section at: https://github.com/felHR85/UsbSerial then import the lib and install dependencies as shown in the url. For solving the problem you can create a service class that handles usb related stuff (look at usb host android documentation for details: https://developer.android.com/guide/topics/connectivity/usb/host.html
as follows:
public class UsbService extends Service {
public static final String TAG = "UsbService";
public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
public static final int CTS_CHANGE = 1;
public static final int DSR_CHANGE = 2;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private IBinder binder = new UsbBinder();
private UsbService context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
/*
* State changes in the CTS line will be received here
*/
private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
#Override
public void onCTSChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(CTS_CHANGE).sendToTarget();
}
};
/*
* State changes in the DSR line will be received here
*/
private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
#Override
public void onDSRChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(DSR_CHANGE).sendToTarget();
}
};
/*
* Different notifications from OS will be received here (USB attached, detached, permission responses...)
* About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
*/
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
connection = usbManager.openDevice(device);
new ConnectionThread().start();
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
if (serialPortConnected) {
serialPort.close();
}
serialPortConnected = false;
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
#Override
public void onCreate() {
this.context=this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
serialPort.close();
unregisterReceiver(usbReceiver);
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
// first, dump the hashmap for diagnostic purposes
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
Log.d(TAG, String.format("USBDevice.HashMap (vid:pid) (%X:%X)-%b class:%X:%X name:%s",
device.getVendorId(), device.getProductId(),
UsbSerialDevice.isSupported(device),
device.getDeviceClass(), device.getDeviceSubclass(),
device.getDeviceName()));
}
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
// if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003) && deviceVID != 0x5c6 && devicePID != 0x904c) {
if (UsbSerialDevice.isSupported(device)) {
// There is a supported device connected - request permission to access it.
requestUserPermission();
break;
} else {
connection = null;
device = null;
}
}
if (device==null) {
// There are no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
Log.d(TAG, "findSerialPortDevice() usbManager returned empty device list." );
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
/*
* Request user permission. The response will be received in the BroadcastReceiver
*/
private void requestUserPermission() {
Log.d(TAG, String.format("requestUserPermission(%X:%X)", device.getVendorId(), device.getProductId() ) );
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
/*
* A simple thread to open a serial port.
* Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
*/
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPortConnected = true;
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
/**
* Current flow control Options:
* UsbSerialInterface.FLOW_CONTROL_OFF
* UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
* UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
*/
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
serialPort.getCTS(ctsCallback);
serialPort.getDSR(dsrCallback);
//
// Some Arduinos would need some sleep because firmware wait some time to know whether a new sketch is going
// to be uploaded or not
//Thread.sleep(2000); // sleep some. YMMV with different chips.
// Everything went as expected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
// Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
// Send an Intent to Main Activity
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
// No driver for given device, even generic CDC driver could not be loaded
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
then in your main activity put this snippets:
java
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
public TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
// Toast.makeText(getApplicationContext(),"dentro on service connected " + usbService, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.operacion);
mHandler = new MyHandler(this);
// your stuff here
#Override
public void onResume() {
super.onResume();
// Toast.makeText(getApplicationContext(),"on resume ", Toast.LENGTH_SHORT).show();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
// Toast.makeText(getApplicationContext(),"despues de start y weas ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
// Toast.makeText(getApplicationContext(),"start1", Toast.LENGTH_SHORT).show();
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
// Toast.makeText(getApplicationContext(),"dp metodo start", Toast.LENGTH_SHORT).show();
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public void getCurrentTimeUsingDate(){
String currentDateTimeString2 = DateFormat.getDateInstance().format(new Date());
TextView txtView3 = (TextView) findViewById(R.id.textView4);
txtView3.setText(""+currentDateTimeString2);
}
private static class MyHandler extends Handler {
private final WeakReference<Pag4> mActivity;
public MyHandler(Pag4 activity) {
mActivity = new WeakReference<>(activity);
}
Integer conta = 0;
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
conta++;
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE",Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE",Toast.LENGTH_LONG).show();
break;
}
}
}
}
you make a button (btn3 in the example) and then add the listener as follows:
java
bt3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String auxi2="1"; // put whatever you need to send here
if (!auxi2.equals("")) {
String data = auxi2;
if (usbService != null) { // if UsbService was correctly binded, Send data
usbService.write(data.getBytes());
// Toast.makeText(getApplicationContext(),"auxi2 escrito"+ auxi2, Toast.LENGTH_SHORT).show();
}
}
}
});
Hope is clear, I assume you know how to import libs, and make a button, put the permission in manifiest, dependencies. Details about this in android doc link already posted upper in my answer.
Hello friends i am creating one android app App lock application in which user can lock the application for that i am using one background service which run in background always. My service is run fine in all device but in some new device like OPPO,Redme Mi and Lenovo Mobile there is one advace feature like user can clean all the running task from the cleaner and because of this advance features when user clean all the task my service also stop and app lock will not work so user need to go in application and manual start the service is there any solution to protect my service from this.
one of app lock have this kind of solution
https://play.google.com/store/apps/details?id=com.domobile.applock
This app service is start after the clean task i also want to do same for my application i tried many solution but not getting any result i my service code is as below
public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;
class C02221 extends BroadcastReceiver {
C02221() {
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
MyAppLockService.this.refreshList();
} else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
MyAppLockService.this.doStopSelf();
} else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
MyAppLockService.this.removeAppFromLockedList(intent
.getStringExtra("packName"));
}
}
}
#SuppressLint("NewApi")
class C02232 extends TimerTask {
C02232() {
}
#SuppressLint("NewApi")
public void run() {
if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
MyAppLockService.this.isRefreshedList = false;
String current = "";
try {
current = Utils.getProcess(
MyAppLockService.this.mUsageStatsManager,
MyAppLockService.this.getApplicationContext());
} catch (Exception e) {
current = "";
}
if (current != null) {
if (MyAppLockService.flag
&& current
.equals(MyAppLockService.this.currentHomePackage)) {
if (MyAppLockService.this.prefs.getBoolean(
"immediately", true)) {
MyAppLockService.locked_list = new DBHelper(
MyAppLockService.this
.getApplicationContext())
.getApsHasStateTrue();
}
MyAppLockService.flag = false;
}
if (!current
.equals(MyAppLockService.this.currentHomePackage)
&& MyAppLockService.locked_list.contains(current)) {
Intent it;
if (MyAppLockService.BuildV >= 23) {
long endTime = System.currentTimeMillis();
UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
.queryEvents(endTime - 10000, endTime);
Event event = new Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
}
if (current.equals(event.getPackageName())
&& event.getEventType() == 1) {
MyAppLockService.pack = current;
if (MyAppLockService.this.prefs.getBoolean(
"isPattern", false)) {
MyAppLockService.this
.confirmPattern(current);
} else {
it = new Intent(
MyAppLockService.this
.getApplicationContext(),
AppLockActivity.class);
it.setFlags(DriveFile.MODE_READ_ONLY);
MyAppLockService.this
.getApplicationContext()
.startActivity(it);
}
MyAppLockService.flag = true;
return;
}
return;
}
MyAppLockService.pack = current;
if (MyAppLockService.this.prefs.getBoolean("isPattern",
false)) {
MyAppLockService.this.confirmPattern(current);
} else {
it = new Intent(
MyAppLockService.this
.getApplicationContext(),
AppLockActivity.class);
it.setFlags(DriveFile.MODE_READ_ONLY);
MyAppLockService.this.getApplicationContext()
.startActivity(it);
}
MyAppLockService.flag = true;
}
}
} else if (!MyAppLockService.this.isRefreshedList) {
MyAppLockService.this.refreshList();
}
}
}
public MyAppLockService() {
this.run = true;
}
static {
BuildV = VERSION.SDK_INT;
}
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
this.prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
this.manager = (ActivityManager) getApplicationContext()
.getSystemService("activity");
this.pmanager = (PowerManager) getApplicationContext()
.getSystemService("power");
if (BuildV >= 21) {
this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
.getSystemService("usagestats");
}
startNotification();
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.HOME");
this.currentHomePackage = getPackageManager().resolveActivity(intent,
Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
this.mReciever = new C02221();
IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
filter.addAction(Utils.ACTION_STOP_SELF);
filter.addAction(Utils.ACTION_REMOVE_APP);
registerReceiver(this.mReciever, filter);
refreshList();
this.tt = new C02232();
this.f6t = new Timer();
this.f6t.schedule(this.tt, 500, 500);
super.onCreate();
Calendar cal = Calendar.getInstance();
Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);
}
public void onDestroy() {
try {
this.f6t.cancel();
this.tt.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent1 = new Intent("com.android.techtrainner");
intent1.putExtra("yourvalue", "torestore");
sendBroadcast(intent1);
}
public void refreshList() {
locked_list = new DBHelper(getApplicationContext())
.getApsHasStateTrue();
if (locked_list.size() == 0) {
doStopSelf();
}
this.isRefreshedList = true;
}
#SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
Calculator_Activity.class), 0);
String title = getString(R.string.app_name);
String content = getString(R.string.app_name);
Builder nb = new Builder(this);
nb.setSmallIcon(R.drawable.ic_transparent);
nb.setContentTitle(title);
nb.setContentText(content);
nb.setWhen(System.currentTimeMillis());
nb.setContentIntent(pi);
nb.setOngoing(true);
nb.setPriority(0);
startForeground(NOTIFICATION_ID, nb.build());
}
private void startNotification() {
startForegroundWithNotification();
if (!this.mShowNotification) {
HelperService.removeNotification(this);
}
}
private void doStopSelf() {
this.mAllowDestroy = true;
unregisterReceiver(this.mReciever);
stopForeground(true);
stopSelf();
}
private void confirmPattern(String st) {
Intent pIntent = new Intent(getApplicationContext(),
ResetActivity.class);
pIntent.putExtra("isFromReset", true);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
12345, pIntent, DriveFile.MODE_READ_ONLY);
Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
getApplicationContext(), LockPatternActivity.class);
intent.putExtra("packName", st);
intent.putExtra("isStealthMode", this.prefs.getBoolean(
AlpSettings.Display.METADATA_STEALTH_MODE, false));
intent.putExtra("isFromLock", true);
intent.setFlags(DriveFile.MODE_READ_ONLY);
intent.addFlags(Cast.MAX_MESSAGE_LENGTH);
intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);
startActivity(intent);
}
private void removeAppFromLockedList(String packName) {
locked_list.remove(packName);
}
if there is any solution for it then please help me out thanks in advance
Restart the service when it's stopped i.e. System will call onDestroy() on service which is stopped.
set a variable in service class to check service is running or not.
let boolRuningService is a variable
Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);
if(!ServiceClass.boolRuningService){
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
}
From what I can tell, the Uri.parse in my code is causing my MediaPlayer to fail on audio files with special characters in the filename, like "#" and others. I cannot figure out how to resolve this issue. I want to be able to use special characters in my filenames. Here is the code that I think is causing the issue:
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
I am using MediaPlayerDemo_Audio.java to play sounds. As you can see from the above code, the mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path)); is calling the code to retrieve the file and media player, I think. I am not too skilled with android code yet. Here is the code for MediaPlayerDemo_Audio.java:
public class MediaPlayerDemo_Audio extends Activity {
public static String path;
private String fname;
private static Intent PlayerIntent;
public static String STOPED = "stoped";
public static String PLAY_START = "play_start";
public static String PAUSED = "paused";
public static String UPDATE_SEEKBAR = "update_seekbar";
public static boolean is_loop = false;
private static final int LOCAL_AUDIO=0;
private Button play_pause, stop;
private SeekBar seek_bar;
public static MediaPlayerDemo_Audio mp;
private AudioPlayerService mPlayerService;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.media_player_layout);
//getWindow().setTitle("SoundPlayer");
//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
// android.R.drawable.ic_media_play);
play_pause = (Button)findViewById(R.id.play_pause);
play_pause.setOnClickListener(play_pause_clk);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(stop_clk);
seek_bar = (SeekBar)findViewById(R.id.seekBar1);
seek_bar.setMax(100);
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayerService!=null) {
int seek_pos = (int) ((double)mPlayerService.getduration()*seekBar.getProgress()/100);
mPlayerService.seek(seek_pos);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
play_pause.setText("Pause");
stop.setText("Stop");
//int idx = path.lastIndexOf("/");
//fname = path.substring(idx+1);
//tx.setText(path);
IntentFilter filter = new IntentFilter();
filter.addAction(STOPED);
filter.addAction(PAUSED);
filter.addAction(PLAY_START);
filter.addAction(UPDATE_SEEKBAR);
registerReceiver(mPlayerReceiver, filter);
PlayerIntent = new Intent(MediaPlayerDemo_Audio.this, AudioPlayerService.class);
if (AudioPlayerService.path=="") AudioPlayerService.path=path;
AudioPlayerService.sound_loop = is_loop;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
if (mPlayerService!=null && mPlayerService.is_pause==true) play_pause.setText("Play");
mp = MediaPlayerDemo_Audio.this;
}
private BroadcastReceiver mPlayerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act.equalsIgnoreCase(UPDATE_SEEKBAR)){
int val = intent.getIntExtra("seek_pos", 0);
seek_bar.setProgress(val);
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (intent.getLongExtra("time", 0)/16.666)));
//tx.setText(fname);
}
else if (act.equalsIgnoreCase(STOPED)) {
play_pause.setText("Play");
seek_bar.setProgress(0);
stopService(PlayerIntent);
unbindService(mConnection);
mPlayerService = null;
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime(0));
}
else if (act.equalsIgnoreCase(PLAY_START)){
play_pause.setText("Pause");
}
else if (act.equalsIgnoreCase(PAUSED)){
play_pause.setText("Play");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mPlayerService = ((AudioPlayerService.LocalBinder)arg1).getService();
if (mPlayerService.is_pause==true) {
play_pause.setText("Play");
seek_bar.setProgress(mPlayerService.seek_pos);
}
if (mPlayerService.mTime!=0) {
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (mPlayerService.mTime/16.666)));
}
if (path.equalsIgnoreCase(AudioPlayerService.path)==false){
AudioPlayerService.path = path;
mPlayerService.restart();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mPlayerService = null;
}
};
private OnClickListener play_pause_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService!=null)
mPlayerService.play_pause();
else{
AudioPlayerService.path=path;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
}
}
};
private OnClickListener stop_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService==null) return;
mPlayerService.Stop();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
}
}
How can I fix this issue so files can be parsed with special characters and played correctly in MediaPlayer? Am I missing something?
Maybe it would help to show the entire code for my AudioPlayerService:
public class AudioPlayerService extends Service {
public MediaPlayer mMediaPlayer;
protected long mStart;
public long mTime;
public int seek_pos=0;
public static boolean sound_loop = false;
public boolean is_play, is_pause;
public static String path="";
private static final int LOCAL_AUDIO=0;
private static final int RESOURCES_AUDIO=1;
private int not_icon;
private Notification notification;
private NotificationManager nm;
private PendingIntent pendingIntent;
private Intent intent;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
CharSequence ticker = "Touch to return to app";
long now = System.currentTimeMillis();
not_icon = R.drawable.play_notification;
notification = new Notification(not_icon, ticker, now);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
intent = new Intent(this, MediaPlayerDemo_Audio.class);
pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if (is_play==true && is_pause==false){
play_pause();
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if (is_play==true && is_pause==false){
play_pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
OnAudioFocusChangeListener myaudiochangelistener = new OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int arg0) {
//if (arg0 ==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
if (is_play==true && is_pause==false){
play_pause();
}
//}
}
};
AudioManager amr = (AudioManager)getSystemService(AUDIO_SERVICE);
amr.requestAudioFocus(myaudiochangelistener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = getApplicationContext();
String title = "VoiceRecorder App";
CharSequence message = "Playing..";
notification.setLatestEventInfo(context, title, message,pendingIntent);
nm.notify(101, notification);
return START_STICKY;
}
public class LocalBinder extends Binder {
AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
public void restart(){
mMediaPlayer.stop();
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
public void Stop()
{
mMediaPlayer.stop();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent1);
resetTimer();
is_play=false;
is_pause=false;
}
public void play_pause()
{
if (is_play==false){
try {
mMediaPlayer.start();
startTimer();
is_play=true;
is_pause = false;
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
}
else{
mMediaPlayer.pause();
stopTimer();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.PAUSED);
sendBroadcast(intent1);
is_play = false;
is_pause = true;
}
}
public int getduration()
{
return mMediaPlayer.getDuration();
}
public void seek(int seek_pos)
{
mMediaPlayer.seekTo(seek_pos);
mTime = seek_pos;
}
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
long curTime = System.currentTimeMillis();
mTime += curTime-mStart;
mStart = curTime;
int pos = (int) ((double)mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration());
seek_pos = pos;
Intent intent1 = new Intent(MediaPlayerDemo_Audio.UPDATE_SEEKBAR);
if (mMediaPlayer.isLooping()) intent1.putExtra("time", (long)mMediaPlayer.getCurrentPosition());
else intent1.putExtra("time", mTime);
intent1.putExtra("seek_pos", pos);
sendBroadcast(intent1);
if (mMediaPlayer.isPlaying()==false && mMediaPlayer.isLooping()==false){
mMediaPlayer.stop();
resetTimer();
Intent intent2 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent2);
is_play=false;
}
if (mTime > 0) mHandler.sendEmptyMessageDelayed(0, 10);
};
};
private void startTimer() {
mStart = System.currentTimeMillis();
mHandler.removeMessages(0);
mHandler.sendEmptyMessage(0);
}
private void stopTimer() {
mHandler.removeMessages(0);
}
private void resetTimer() {
stopTimer();
mTime = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
nm.cancel(101);
}
}
For local files, do not use Uri.parse(). Use Uri.fromFile(), passing in a File object pointing to the file in question. This should properly escape special characters like #.