Close(kill) another app in my application by package name - xamarin.android

I would like to close(kill) another app in my application by package name. I am trying something like this, but this code don't close any app. what am i doing wrong?
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
IList<RunningAppProcessInfo> runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.SendSignal(runningProcess.Pid, Signal.Kill);
am.KillBackgroundProcesses(runningProcess.ProcessName);
}
}
}
P.S I added android.permission.KILL_BACKGROUND_PROCESSES and by this code i can close only my own app

If you want to kill a background app , check the following code
public void amKillProcess(string package_name)
{
ActivityManager am = (ActivityManager)this.GetSystemService(Context.ActivityService);
var runningProcesses = am.RunningAppProcesses;
foreach (RunningAppProcessInfo runningProcess in runningProcesses)
{
if (runningProcess.ProcessName.Contains(package_name))
{
Android.OS.Process.KillProcess(runningProcess.Uid);
}
}
}
And if you want to kill a foreground app, you could use Adb
public class SuUtil
{
private static Java.Lang.Process process;
public static void kill(string packageName)
{
initProcess();
killProcess(packageName);
close();
}
private static void initProcess()
{
if (process == null)
try
{
process = Runtime.GetRuntime().Exec("su");
}
catch (IOException e)
{
}
}
private static void killProcess(string packageName)
{
System.IO.Stream output = process.OutputStream;
Java.Lang.String cmd = new Java.Lang.String("am force-stop " + packageName + " \n");
try
{
output.Write(cmd.GetBytes());
output.Flush();
}
catch (IOException e)
{
}
}
private static void close()
{
if (process != null)
try
{
process.OutputStream.Close();
process = null;
}
catch (IOException e)
{
}
}
}

Related

Vaadin upload with PipedInputStream & PipedOutputStream example

I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.

xamarin.forms android service run twice after restarting it

I have this code that create an android service
[Service]
public abstract class LongRunningTaskService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Logs.Info("service started: " + this.GetType().ToString());
try
{
Tasks.RunTask(() =>
{
try
{
Task.run(() => SomeTaskFunction);
StopSelf();
Logs.Info("service ended successfully from main task");
}
catch (Android.OS.OperationCanceledException e)
{
Logs.Warning("Error in Tasks.RunTaskWithoutWaitForResult", e);
}
});
return StartCommandResult.NotSticky;
}
catch (Exception e)
{
Logs.Warning("error in OnStartCommand", e);
return StartCommandResult.NotSticky;
}
}
public override void OnDestroy()
{
try
{
Logs.Info("service destroyed: " + this.GetType().ToString());
base.OnDestroy();
}
catch (Exception e)
{
Logs.Warning("Error in service destroyed: " + this.GetType().ToString(), e);
}
}
}
when i create the service the first time it works ok, but when i destroy it from outside the service and recreate it with the same function to run there are 2 tasks running at the same time.
what am i doing wrong ?

Suspended (exception IlegalStateException) blackberry 6.0

Following is the code which is showing the above exception on debugging :
Firstly I am trying to call a class HTTPConnection from the below menu item.
protected MenuItem _SelectDealerItem = new MenuItem("Select Dealer",100,10)
{
public void run()
{
new HTTPConnection();
}
};
In HTTPConnection Class I am checking the connection type and calling another Class TSelectDealerScreen:
public class HTTPConnection {
ConnectionFactory _factory = new ConnectionFactory();
public HTTPConnection()
{
int[] _intTransports = {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_WAP2,
TransportInfo.TRANSPORT_TCP_CELLULAR
};
for(int i=0;i<_intTransports.length;i++)
{
int transport = _intTransports[i];
if(!TransportInfo.isTransportTypeAvailable(transport)||!TransportInfo.hasSufficientCoverage(transport))
{
Arrays.removeAt(_intTransports,i);
}
}
TcpCellularOptions tcpOptions = new TcpCellularOptions();
if(!TcpCellularOptions.isDefaultAPNSet())
{
tcpOptions.setApn("My APN");
tcpOptions.setTunnelAuthUsername("user");
tcpOptions.setTunnelAuthPassword("password");
}
if(_intTransports.length>0)
{
_factory.setPreferredTransportTypes(_intTransports);
}
_factory.setTransportTypeOptions(TransportInfo.TRANSPORT_TCP_CELLULAR, tcpOptions);
_factory.setAttemptsLimit(5);
Thread t = new Thread(new Runnable()
{
public void run()
{
ConnectionDescriptor cd = _factory.getConnection("http://excellentrealtors.info/Smart-Trace/get_dealer.php");
if(cd!=null)
{
Connection c = cd.getConnection();
displayContent(c);
}
}
});
t.start();
}
private void displayContent(final Connection conn)
{
UiApplication.getUiApplication().pushScreen(new TSelectDealerScreen(conn));
}
}
In TSelectDealerScreen class i am simply trying to read the stream, but it is showing illegal state exception whenever i try to debug, I am not much familiar to blackberry programming, kindly advice.
public class TSelectDealerScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public TSelectDealerScreen(Connection conn)
{
_rtfOutput.setText("Retrieving Data.Please Wait");
add(_rtfOutput);
ContentReaderThread t = new ContentReaderThread(conn);
t.start();
}
private final class ContentReaderThread extends Thread {
private Connection _connection;
ContentReaderThread(Connection conn)
{
_connection = conn;
}
public void run()
{
String result = "";
OutputStream os = null;
InputStream is = null;
try
{
OutputConnection outputConn = (OutputConnection)_connection;
os = outputConn.openOutputStream();
String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
os.write(getCommand.getBytes());
os.flush();
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) _connection;
is = inputConn.openInputStream();
byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
result = new String(data, "US-ASCII");
// is.close();
System.out.print(result);
}
catch(Exception e)
{
result = "ERROR fetching content: " + e.toString();
}
finally
{
// Close OutputStream
if(os != null)
{
try
{
os.close();
}
catch(IOException e)
{
}
}
// Close InputStream
if(is != null)
{
try
{
is.close();
}
catch(IOException e)
{
}
}
// Close Connection
try
{
_connection.close();
}
catch(IOException ioe)
{
}
}
// Show the response received from the web server, or an error message
showContents(result);
}
}
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
In your HTTPConnection class, you do:
Thread t = new Thread(new Runnable()
{
public void run()
{
ConnectionDescriptor cd = _factory.getConnection("http://excellentrealtors.info/Smart-Trace/get_dealer.php");
if(cd!=null)
{
Connection c = cd.getConnection();
displayContent(c);
}
}
});
t.start();
That runs everything inside run() on a background thread. But, inside displayContent(c), you do:
UiApplication.getUiApplication().pushScreen(new TSelectDealerScreen(conn));
which is a UI operation.
Trying to modify the UI from a background thread normally causes an IllegalStateException.
I believe you just need to wrap the call to pushScreen() with this:
private void displayContent(final Connection conn) {
final UiApplication app = UiApplication.getUiApplication();
app.invokeLater(new Runnable() {
public void run() {
// this code is run on the UI thread
app.pushScreen(new TSelectDealerScreen(conn));
}
});
}
Also, if you're an Android developer, and you want help doing normal background/UI thread stuff, you might check out this other answer I wrote on "porting" AsyncTask to BlackBerry Java

Launch the video recorder from BlackBerry app

Are there any APIs to launch the video recording app? I want to invoke the video recorder through my app, record a video, then save that video to the server.
ApplicationManager.getApplicationManager().launch("net_rim_bb_videorecorder");
This will help you open the application. If you want to start recording, you may need to simulate a key input.
btw: CameraArguments(ARG_VIDEO_RECORDER) is introduced since jde4.7, so it's not compatible with the previous OS's. So the previous method is better.
Finally find the solution from BB docs .
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.lang.*;
import javax.microedition.media.*;
import java.io.*;
import javax.microedition.media.control.*;
public class VideoRecordingDemo extends UiApplication
{
public static void main(String[] args)
{
VideoRecordingDemo app = new VideoRecordingDemo();
app.enterEventDispatcher();
}
public VideoRecordingDemo()
{
pushScreen(new VideoRecordingDemoScreen());
}
private class VideoRecordingDemoScreen extends MainScreen
{
private VideoRecorderThread _recorderThread;
public VideoRecordingDemoScreen()
{
setTitle("Video recording demo");
addMenuItem(new StartRecording());
addMenuItem(new StopRecording());
}
private class StartRecording extends MenuItem
{
public StartRecording()
{
super("Start recording", 0, 100);
}
public void run()
{
try
{
VideoRecorderThread newRecorderThread = new VideoRecorderThread();
newRecorderThread.start();
_recorderThread = newRecorderThread;
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class StopRecording extends MenuItem
{
public StopRecording()
{
super("Stop recording", 0, 100);
}
public void run()
{
try
{
if (_recorderThread != null)
{
_recorderThread.stop();
}
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class VideoRecorderThread extends Thread implements javax.microedition.media.PlayerListener
{
private Player _player;
private RecordControl _recordControl;
VideoRecorderThread()
{
}
public void run()
{
try
{
_player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=video/3gpp");
_player.addPlayerListener(this);
_player.realize();
VideoControl videoControl = (VideoControl) _player.getControl("VideoControl");
_recordControl = (RecordControl) _player.getControl( "RecordControl" );
Field videoField = (Field) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
try
{
videoControl.setDisplaySize( Display.getWidth(), Display.getHeight() );
}
catch( MediaException me )
{
// setDisplaySize is not supported
}
add(videoField);
_recordControl.setRecordLocation("file:///store/home/user/VideoRecordingTest.3gpp" );
_recordControl.startRecord();
_player.start();
}
catch( IOException e )
{
Dialog.alert(e.toString());
}
catch( MediaException e )
{
Dialog.alert(e.toString());
}
}
public void stop()
{
if (_player != null)
{
_player.close();
_player = null;
}
if (_recordControl != null)
{
_recordControl.stopRecord();
try
{
_recordControl.commit();
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
_recordControl = null;
}
}
public void playerUpdate(Player player, String event, Object eventData)
{
Dialog.alert("Player " + player.hashCode() + " got event " + event + ": " + eventData);
}
}
}
}

Blackberry screen renew with new data

I am developing a Blackberry Application. I have a map in a screen. I want to refresh map's data with new data which i am getting from my web service. I am using BlockingSenderDestination in a Thread. When i request "get data" its return new data. no problem. I am using invokelater function to call my maprefresh function with passing arguments but i got illegalargumentexception.
Any suggestion to solve my problem or any better way to do this?
Here is my code:
public class MyMainScreen extends MainScreen {
RichMapField map;
MyClassList _myclassList;
private String _result2t;
public MyMainScreen(JSONArray jarray)
{
map = MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
private void GetTerminals(String companyNo){
final String companyNoR= companyNo;
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://webservice";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("o", URI.create(uriStr));
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("o"),
URI.create(uriStr)
);
}
response = bsd.sendReceive();
if(response != null)
{
BSDResponse(response,companyNoR);
}
}
catch(Exception e)
{
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
private void BSDResponse(Message msg,final String companyNo)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result2t = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result2t = new String(data);
}
}
try {
final JSONArray jarray= new JSONArray(_result2t);
final String username=_userName;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("The Toolbar i");
Yenile(jarray);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Yenile(JSONArray jarray){
MapDataModel mapDataModel = map.getModel();
mapDataModel.remove("1");
map.getMapField().update(true);
_terminalList = new TerminalList();
map= MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray_terminaller.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
}
To refresh the screen: do like this:
public class LoadingScreen extends MainScreen{
LoadingScreen()
{
createGUI();
}
public void createGUI()
{
//Here you write the code that display on screen;
}}
we know that this is the actual way of creating a screen;
Now if you want to refresh the screen write like below:
deleteAll();
invalidate();
createGUI();//here it creates the screen with new data.
Instead of writing in InvokeLater method better to write the above three lines in run method after Thread.sleep(10000);
If you have any doubts come on stackOverFlow chat room name "Life for Blackberry" for clarify your and our doubts.
I found a solution to my question.
After getting the data i was sending it via new run method:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
MyFunction(jarray);
}});
But i was need to synchronize with main thread. So the solution:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized(Application.getEventLock()) {
Yenile(jarray);
}
}
});

Resources