So yeah, my thread isn't executing, or doing the code within it. I just wanted to run a shell script from my sdcard, and show a "loading" circles or "progress" circle or whatever you want to call it. When I click the button to run the thread, I get the progress/loading bar/circle, but it just sits there and does nothing. I've looked at some examples but still cannot figure out what I did wrong. Here's my code:
package com.cydeon.plasmamodz;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeoutException;
import com.stericson.RootTools.*;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Install extends Activity{
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install);
Button bInstall = (Button) findViewById(R.id.bInstallTheme);
bInstall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog();
}
});
}
public void showDialog(){
progressDialog = ProgressDialog.show(Install.this, "", "Installing Theme", true);
Thread thread = new Thread();
thread.start();
}
public void run(){
try{
Thread.sleep(1000);
CommandCapture command = new CommandCapture(0, "su", "sh /sdcard/plasma/scripts/install.sh");
try {
RootTools.getShell(true).add(command).waitForFinish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (RootDeniedException e) {
e.printStackTrace();
}
}catch (InterruptedException e){
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private static Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
So, am I doing something wrong? Why won't it run my code? Thanks!
The thread doesn't know what to run. Change
public class Install extends Activity{
to
public class Install extends Activity implements Runnable {
and change
Thread thread = new Thread();
to
Thread thread = new Thread(this);
Related
I tried unzipping a zip file with password But it goes to a dead end. Like It says No read permission. I requested the permission from the code and allowed in app. Still error coming
Error - net.lingala.zip4j.exception.ZipException: no read access for the input zip file
This is the code
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.ZipFile;
public class MainActivity2 extends AppCompatActivity {
;
private FileChooserFragment fragment;
private Button buttonShowInfo;
Context context;
String vv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.buttonShowInfo = this.findViewById(R.id.button_showInfo);
this.buttonShowInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
showInfo();
} catch (ZipException e) {
e.printStackTrace();
}
}
});
}
private void showInfo() throws ZipException {
try {
//
System.out.println(Environment.getExternalStorageDirectory().toString());
ZipFile zipFile = new ZipFile("/storage/emulated/0/Download/1.zip);
if (zipFile.isEncrypted()) {
zipFile.setPassword("aa".toCharArray());
}
zipFile.extractAll(Environment.getExternalStorageDirectory().toString());
break;
} catch (ZipException e) {
System.out.println("nope");
e.printStackTrace();
}
}}
Password is aa
Please give me a code which works in new version of android studio and android 11 atleast
I want my app to write to my bluetooth receiver commend until i hold a button, then the commend will change and continue when i release. (it will send 0 always until i will hold, and then it will send 1 and when i release 0 again).
I tried to make a thread it will send the 0 that is working but when i hold the button it sends 1(as intened) but when i release it doesnt sends 0 again.
package com.example.bluetooth;
import static android.text.TextUtils.concat;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private OutputStream outputStream;
Spinner spinner;
ArrayList<String> deviceName = new ArrayList<String>();
Map<String, String> devicesDict = new HashMap<String, String>();
Object[] devices;
EditText InputTI;
Button sendB;
Button commend1B;
String message;
Boolean connected = false;
Boolean sending = false;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
devices = (Object []) bondedDevices.toArray();
Log.i("devices:","devices[0]"+devices[0]);
Log.i("devices:","devices[1]"+devices[1]);
Log.i("devices:","devices[2]"+devices[2]);
BluetoothDevice result = null;
for (BluetoothDevice device : bondedDevices) {
devicesDict.put(""+device.getName(), ""+device);
}
Log.i("dict","dict"+devicesDict);
deviceName.add("Select:");
for(Map.Entry<String,String> entry : devicesDict.entrySet()){
deviceName.add(entry.getKey()+";"+entry.getValue());
}
spinner = (Spinner) findViewById(R.id.ListSp);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, deviceName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
InputTI = findViewById(R.id.InputTI);
sendB = findViewById(R.id.sendB);
commend1B = findViewById(R.id.commend1B);
Thread thread = new Thread(runnable);
commend1B.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
sending = true;
try {
Log.i("sending","sending 1");
write("1#");
} catch (IOException e) {
e.printStackTrace();
}
sending = false;
return false;
}
});
sendB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("sendState","state"+sending);
message = InputTI.getText().toString()+"#";
try {
write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String[] splitted;
splitted = adapterView.getSelectedItem().toString().split(";");
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
if (!adapterView.getSelectedItem().toString().equals("Select:")) {
for (Object o : devices) {
if (o.toString().equals(splitted[1])) {
connected = true;
BluetoothDevice device = (BluetoothDevice) o;
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.connect();
} catch (IOException e) {
Log.e("ConnectFail", "Socket.connect() Failed", e);
//e.printStackTrace();
break;
}
try {
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
if (connected && !sending) {
Log.i("sending", "sending 021");
thread.start();
}
}
}
}else{
connected = false;
}
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
Runnable runnable = new Runnable(){
public void run() {
while (connected && !sending) {
try {
Log.i("sending", "sending 0");
write("0#");
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
To run background services you need to use Service class or/and Background Threads.
Service documentation: https://developer.android.com/guide/components/services
BackGround Threads: https://developer.android.com/guide/background/threading
I am new in android, I am trying to implement socket in android it is a simple client-server app.
where I have created 2 buttons ("connect", "disconnect"), and using AysncTask doInBackground i am connecting to the server and disconnecting from the server but it's working for connection only, when I am trying to disconnect my app close unfortunately.
Below there is my mainactivity code.
Thanks for helping
package com.example.sockettest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import java.io.*;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.lang.String;
class conn extends AsyncTask<String, Void, Void>{
Socket operator_socket;
#Override
protected Void doInBackground(String... voids) {
String str;
str = voids[0];
if (str.equals("conn")) {
try {
operator_socket = new Socket("192.168.0.103", 6666);
}catch (UnsupportedEncodingException e) { e.printStackTrace(); }
catch (UnknownHostException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
} else if (str.equals("CC")){
try {
operator_socket.getOutputStream().write("EX".getBytes("US-ASCII"));
operator_socket.close();
} catch (UnsupportedEncodingException e) { e.printStackTrace(); }
catch (UnknownHostException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
} else {
}
return null;
}
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
conn new_conn = new conn();
public void connect_operator(View v){
new_conn.execute("conn");
}
public void close_conn(View v){ new_conn.execute("CC"); }
}
You can call execute only once on one instance of an AsyncTask. new_conn is being initialised only once. Now if you try to create a new object every time to call execute, you won't be able to use operator_socket Socket variable as a member variable of AsyncTask class. You are getting exception when calling execute more than once on a single instance of AsyncTask
Read these docs
I am trying to read a text file from SD-Card in a Runnable called PcmDataReader and updating a TextView statusTextView , accordingly in the UI-Thread.
I am using a handler to pass the messages from PcmDataReader to the UI-Thread.
In order to be able to observe the change of statusTextView I have put a Thread.sleep(5000) in PcmDataReader.
The issue is that the UI-Thread is blocked until the file i/o & the sleep are finished & the final update i.e. "File Reading Complete.." is only shown on statusTextview.
What am I missing here ? Following is my code:
MainActivity.java:
package com.example.pcmreader;
import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView statusTextView ;
priavte Button updateButton;
private PcmDataReader pcmData = new PcmDataReader();
private static Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
handler = new Handler()
{
#Override
public void handleMessage (Message message)
{
String msg = (String) message.obj;
if (statusTextView != null)
statusTextView.setText(msg);
}
};
setContentView(R.layout.main);
statusTextView= (TextView) findViewById(R.id.statusTextView);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 100);
updateButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
statusTextView.setText("Initiating Read .. ");
pcmData.run();
}
public static Handler getHandler ()
{
return handler;
}
}
PcmDataReader.java:
package com.example.pcmreader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PcmDataReader implements Runnable
{
private int [] samples = new int[6000];
private int i;
private boolean completedReading;
private File sdcard = Environment.getExternalStorageDirectory();
private File file = new File(sdcard,"rishav_log.txt");
#Override
public void run()
{
i=0;
completedReading = false;
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
Handler uiHandler= MainActivity.getHandler();
Message msg = uiHandler.obtainMessage();
msg.obj="File openned, Reading data..";
uiHandler.sendMessage(msg);
while ((line = br.readLine()) != null)
samples[i++]=Integer.parseInt(line);
Thread.sleep(5000); //dummy sleep to observe the update of textView in UI thead
br.close();
completedReading = true;
msg = uiHandler.obtainMessage();
msg.obj="File Reading Complete..";
uiHandler.sendMessage(msg);
}
catch (IOException e)
{
Log.i("file read",e.getMessage());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
Calling runnable should be in separate thread.
Replace
pcmData.run();
to
Thread t1 =new Thread(pcmData);
t1.start();
The UI thread freezes because you call the Thread.sleep() in the same thread:
#Override
public void onClick(View view) {
statusTextView.setText("Initiating Read .. ");
pcmData.run(); // PcmDataReader.run() will happen in the UI thread
}
The fix is relatively easy:
#Override
public void onClick(View view) {
statusTextView.setText("Initiating Read .. ");
ExecutorService executor = Executors.newSingleThreadExecutor(); // this can come from somplace else.
// Actually, it better comes from someplac else.
executor.submit(pcmData); // this is how to run in in a background thread.
// executor.shutdown(); // this is necessary only if you create the executor in the same method.
// Otherwise, creating and killing background threads is a matter of your apps strategy.
}
package islam.work;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class Tasbeeeee7_IslamicActivity extends Activity {
MediaPlayer begin;
Intent inti;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
begin = MediaPlayer.create(Tasbeeeee7_IslamicActivity.this, R.drawable.media);
begin.start();
Thread timer = new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally
{
inti = new Intent(this, program.class); //error here
startActivity(inti);
}
}
};
timer.start();
}
}
Change
inti = new Intent(this, program.class);
to
inti = new Intent(Tasbeeeee7_IslamicActivity .this, program.class);
Since you are constructing your Intent inside of a Thread, this is referring to the Thread instead of your Activity Context.