I am trying to block facebook on system browser - android

For this,first i am getting the top activity from the stack and then matching the string of Facebook in logcat..
I am using this Code,
public class MyService extends Service
{
public static String Tag = "Task";
public static String Tag1 = "Top Running Task";
ActivityManager am ;
String packageName ;
Handler handler;
int count=0;
#Override
public int onStartCommand(Intent intent,int flags, int startId)
{
// TODO Auto-generated method stub
super.onStartCommand(intent, flags,startId);
Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();
handler = new Handler(){
#Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
super.handleMessage(msg);
// Browser.clearHistory(getContentResolver());
//Browser.clearSearches(getContentResolver());
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
if((packageName).indexOf("browser")!= -1)
{
// Toast tost=Toast.makeText(getApplicationContext(), packageName.toString(), 1);
//tost.show();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
if(line.contains("facebook.com"))
{
//Browser.addSearchUrl(getContentResolver(), "google");
Log.i(Tag1,"ww"+ line);
/*Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);*/
//android.os.Process.killProcess(pid);
}
//log.;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//}
}
};
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
handler.sendEmptyMessage(0);
}
catch (InterruptedException e) {}
}
}
}).start();
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
am.killBackgroundProcesses(packageName);
Log.i(Tag,"destory ");
}
#Override
public IBinder onBind(Intent intent)
{
//TODO for communication return IBinder implementation
return null;
}
}
I am deleting the History and cache too.
After that,i am able to block facebook but first time,it works fine but second time it does not work,it keeps its history for 5-6 seconds and after that again worked fine.

Related

AsyncTask not called in service

Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}

passing data from BroadcastReceiver to class that extends runnable

My goal is to create a method that gets the data from broadcast receiver and sends it trough a socket. I know how to send it, but how can i get a data from BroadcastReceiver ? I want to receive data in this class:
public class ClientThread implements Runnable{
Socket socket;
public final String TAG = "CLIENT";
ObjectOutputStream os;
TextView text;
Handler handler;
AppHelper helperClass;
Activity mActivity;
Context mContext;
public ClientThread(Activity mActivity,TextView text,Context context) {
// TODO Auto-generated constructor stub
this.text=text;
this.mContext=context;;
helperClass = new AppHelper(context, mActivity);
handler = new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket
.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
String line = null;
while ((line = in.readUTF().toString()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
if (mesg.contains("getcontacts")) {
try {
sendContacts();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (mesg.contains("getmsg")) {
getMessages();
} else if (mesg.contains("sendmsg")) {
sendMessage(mesg);
} else {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
public void receivedMessage(String sender, String message) {
}
private void sendMessage(String s) {
String[] x = s.split(" ");
int lenght = x.length;
String message = x[2];
for (int i = 3; i < x.length; i++) {
message = message + " " + x[i];
}
System.out.println(message);
SmsManager smsManager = SmsManager.getDefault();
System.out.println("sending message");
smsManager.sendTextMessage(x[1], null, message, null, null);
System.out.println("message send");
}
private void sendContacts() throws IOException {
final List<Person> list = helperClass.getContacts();
final String json = new Gson().toJson(list);
Log.i(TAG, "lenght " + json.length());
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
os.writeObject(json);
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Sending Contact list has failed");
e.printStackTrace();
}
}
});
}
private void getMessages() {
// TODO Auto-generated method stub
ProgressTask task = new ProgressTask();
ProgressTask.execute(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<Sms> sms = helperClass.getAllSms();
final String json = new Gson().toJson(sms);
os.writeObject(json);
os.flush();
System.out.println("List of messages send");
} catch (Exception e) {
Log.e(TAG, "Sending Contact list has failed");
}
}
});
}
}
You may use an interface as listener to this runnable.
Create a Listener interface
Declare Interface Variable in Application Context.
Instantiate and implement interface in Runnable class.
In BroadcastReciever, call method of that interface.
Ex:
Class A extends Application{
public Listener listener;
}`
interface Listener{
public void yourmethod();
}
In Your clientthread method instantiate listener as follows:
((A)context.getApplication()).listener = new Listener(){
#override
public void yourmethod(){
// your implementation goes here
}
}
In your broadcast reciever.
((A)context.getApplication()).listener.yourmethod();

onStartCommand Call after Destroying an Activity

i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue

InstantiationException occur while Downloading using Service

I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?
Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService

java.lang.NullPointerException at android.content.ContextWrapper.getPackageManager

I am getting this error
java.lang.NullPointerException at android.content.ContextWrapper.getPackageManager
when am trying to get list of all installed applications on the device.
I have a server that starts when my application is started, and the client pings the server and asks to get a list of installed applications. The Server then asks the getPackageManager() and gets all the installed applications.
But the getPackageManager throws a NullPointerException.
The Server is written in a java and is started from my android application.
Could someone please tell me what am missing and why I am getting this error?
Please find the code below
public class ApplicationRecognition extends Activity {
// android.os.Debug.waitForDebugger();
Button buttonStart, buttonStop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
final SecurityModuleServer server = new SecurityModuleServer(5902);
server.start();
Toast.makeText(this, "Application Server is started", Toast.LENGTH_SHORT).show();
buttonStart.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startService(new Intent(getBaseContext(), AppReconService.class));
}});
buttonStop.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
stopService(new Intent(getBaseContext(), AppReconService.class));
}});
}
public String[] getInstalledApplications()
{
String[] appname =new String[10];
Intent mainIntent = new Intent(Intent.ACTION_MAIN,null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager manager = getPackageManager();
List<ResolveInfo> pkgAppsList = manager.queryIntentActivities(mainIntent, 0);
appname = new String[pkgAppsList.size()];
for(int i=0;i<pkgAppsList.size();i++)
{
appname[i]=pkgAppsList.get(i).activityInfo.packageName;
}
return appname;
}
}
the server side code
public class SecurityModuleServer implements Observer,Runnable
{
private int numberOfConnectedClient;
private Thread serverThread;
private ServerSocket serverSocket;
private volatile boolean isServerRunning;
public SecurityModuleServer(final int port)
{
numberOfConnectedClient = 0;
try
{
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
System.out.println("SecurityModuleServer>> server thread started."); //$NON-NLS-1$
while(isServerRunning)
{
numberOfConnectedClient++;
try
{
SecurityModuleClientThread client = new SecurityModuleClientThread(serverSocket.accept(), numberOfConnectedClient);
client.addObserver(this);
client.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("SecurityModuleServer>> server thread stopped."); //$NON-NLS-1$
}
synchronized public void start()
{
serverThread = new Thread(this);
isServerRunning = true;
serverThread.start();
}
synchronized public void stop()
{
isServerRunning = false;
}
public boolean isRunning()
{
return isServerRunning;
}
public static void main(String[] args)
{
SecurityModuleServer server = new SecurityModuleServer(5903);
server.start();
}
public void update(Observable o, Object arg)
{
numberOfConnectedClient--;
}
}
the client side code
public SecurityModuleClientThread(Socket socket, int numberOfClient)
{
clientSocket = socket;
numberOfConnectedClient = numberOfClient;
try
{
printOut = new PrintStream(clientSocket.getOutputStream());
readerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientThread = new Thread(this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
Looper.prepare();
String input = ""; //$NON-NLS-1$
System.out.println("SecurityModuleClientThread>> thread started for client."); //$NON-NLS-1$
if (numberOfConnectedClient <= MAX_ALLOWED_CLIENTS)
{
printOut.println(CMD+Answer_Open_Connection+SEPARATOR+M002);
while(isClientRunning)
{
try
{
input = readerIn.readLine();
System.out.println("Message received>> "+input); //$NON-NLS-1$
parseInputMessage(input);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M003);
stop();
}
System.out.println("SecurityModuleClientThread>> thread stopped for client."); //$NON-NLS-1$
}
private void parseInputMessage(final String input)
{
if (input.equalsIgnoreCase(CMD+Request_Close_Connection))
{
printOut.println(CMD+Answer_Close_Connection+SEPARATOR+M007);
stop();
}
else
{
String messages[] = input.split(SEPARATOR);
// Parse the command
switch(parseCommand(messages[0]))
{
case Request_Start_Application:
if(parseApplicationName(input) != null)
{
if(startAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Start_Application);
startAndroidApplication(parseApplicationName(input));
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Stop_Application:
if(parseApplicationName(input) != null)
{
if (stopAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Stop_Application);
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Application_Installed:
String[] appnames = new String[provideInstalledApplication().length];
appnames = provideInstalledApplication();
for(int i=0;i<appnames.length;i++)
{
printOut.println(appnames[i]);
}
break;
case Request_Application_Running:
//TODO
break;
default:
printOut.println(CMD+Error+SEPARATOR+M008);
break;
}
}
}
private int parseCommand(String cmd)
{
if (cmd.length() == 6)
{
return Integer.parseInt(cmd.substring(3, 6));
}
else
{
return 0;
}
}
private String parseApplicationName(String message)
{
if (message.length() > 6)
{
// TODO
return message.substring(6, message.length());
}
else
{
return null;
}
}
public synchronized void start()
{
isClientRunning = true;
clientThread = new Thread(this);
clientThread.start();
}
public synchronized void stop()
{
printOut.close();
try
{
readerIn.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
isClientRunning = false;
setChanged();
notifyObservers();
}
}
public boolean isRunning()
{
return isClientRunning;
}
public String[] provideInstalledApplication()
{
String[] appnames = null;
ApplicationRecognition apprecon = new ApplicationRecognition();
appnames=new String[apprecon.getInstalledApplications().length];
appnames = apprecon.getInstalledApplications();
return appnames;
}
public String[] provideRunningApplication()
{
// TODO Auto-generated method stub
return null;
}
public boolean startAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
ApplicationRecognition apprecon = new ApplicationRecognition();
apprecon.startApplication(applicationName);
return false;
}
public boolean stopAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
return false;
}
}
The main part that is giving me trouble is in ApplicationRecognition class under method getInstalledApplications() in getPackageManager is null.
This method is called from the client side SecurityModuleClientThread class, provideInstalledApplication method.
Can someone please tell me where am I going wrong.

Categories

Resources