I have created a hotspot from my windows7 machine and trying to write a code to connect my android phone to that hotspot.
I have been able to connect the phone.
Further I am trying to modify the proxy settings like IP and port for the connected hotspot using the code.
The phone is connecting to the hotspot but the code is unable to modify the proxy settings.
The code I have written is as follows:
Main_activity.java
I am connecting wifi hotspot created in vb.net and then connecting phone to that hotspot
` Package com.example.connect_avek;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ProxyInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import static android.widget.Toast.LENGTH_LONG;
public class MainActivity extends Activity {
Button startbtn,stopbtn;
RelativeLayout background;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startbtn = (Button)findViewById(R.id.startbtn);
stopbtn = (Button)findViewById(R.id.stopbtn);
startbtn.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View v) {
//start connection code
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + "shashank" + "\""; // Please note the quotes. String should contain SSID in quotes
wc.preSharedKey = "\"" + "mummy#123" + "\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
Log.d("connecting", wc.SSID + " " + wc.preSharedKey);
wifi.addNetwork(wc);
Log.d("after connecting", wc.SSID + " " + wc.preSharedKey);
List<WifiConfiguration> list = wifi.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + "shashank" + "\"")) {
wifi.disconnect();
wifi.enableNetwork(i.networkId, true);
wifi.reconnect();
Log.d("re connecting", i.SSID + " " + wc.preSharedKey);
try {
Class proxyInfoClass = Class.forName("android.net.ProxyInfo");
Class[] setHttpProxyParams = new Class[1];
setHttpProxyParams[0] = proxyInfoClass;
Class wifiConfigClass = Class.forName("android.net.wifi.WifiConfiguration");
Method setHttpProxy = wifiConfigClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
setHttpProxy.setAccessible(true);
//Method 1 to get the ENUM ProxySettings in IpConfiguration
Class ipConfigClass = Class.forName("android.net.IpConfiguration");
Field f = ipConfigClass.getField("proxySettings");
Class proxySettingsClass = f.getType();
//Method 2 to get the ENUM ProxySettings in IpConfiguration
//Note the $ between the class and ENUM
//Class proxySettingsClass = Class.forName("android.net.IpConfiguration$ProxySettings");
Class[] setProxySettingsParams = new Class[1];
setProxySettingsParams[0] = proxySettingsClass;
Method setProxySettings = wifiConfigClass.getDeclaredMethod("setProxySettings", setProxySettingsParams);
setProxySettings.setAccessible(true);
ProxyInfo pi = ProxyInfo.buildDirectProxy("192.168.137.1", 7777);
//Android 5 supports a PAC file
//ENUM value is "PAC"
//ProxyInfo pacInfo = ProxyInfo.buildPacProxy(Uri.parse("http://localhost/pac"));
//pass the new object to setHttpProxy
Object[] params_SetHttpProxy = new Object[1];
params_SetHttpProxy[0] = pi;
setHttpProxy.invoke(wc, params_SetHttpProxy);
//pass the enum to setProxySettings
Object[] params_setProxySettings = new Object[1];
params_setProxySettings[0] = Enum.valueOf((Class<Enum>) proxySettingsClass, "STATIC");
setProxySettings.invoke(wc, params_setProxySettings);
//save the settings
wifi.updateNetwork(wc);
wifi.disconnect();
wifi.reconnect();
} catch (Exception e) {
Log.v("wifiProxy", e.toString());
}
}
break;
}
}
});
stopbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//stop connection code
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
}
} `
-----------------------------------------------------------------------------
**manifest.xml**
I have added the wifi permissions for the internet state and activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.connect_avek" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
----------------------------------------------------------------------------
Related
Below is my MainActivity and Manifest file. I am trying to implement a screenshot in my app which then gives the option to open the screenshot using other applications. When I click the button in the main activity nothing is happening. It keeps throwing java.io.FileNotFoundException like so
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/ScreenShooter/2021-02-19_07:45:59.jpg: open failed: ENOENT (No such file or directory)
Is there a way to solve this?
package com.levirs.example.screenshooter;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
screenshoot();
}
});
}
private void screenshoot() {
Date date = new Date();
CharSequence now = android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", date);
String filename = Environment.getExternalStorageDirectory() + "/ScreenShooter/" + now + ".jpg";
View root = getWindow().getDecorView();
root.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(root.getDrawingCache());
root.setDrawingCacheEnabled(false);
File file = new File(filename);
file.getParentFile().mkdirs();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.levirs.example.screenshooter">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
its seems like you are access the directory which not exist make sure its exist if you are using default screenshots folder then replace this line
Environment.getExternalStorageDirectory() + "/ScreenShooter/" + now + ".jpg";
to
Environment.getExternalStorageDirectory() + "/Pictures/Screenshots/" + now + ".jpg";
but this getExternalStorageDirectory is depricated now so use this one
getFilesDir()+ "/Pictures/Screenshots/" + now + ".jpg";
You're trying to instance a file on a path only via string which represents path+fileName.
Instead you should instance a new File with path separated from the fileName.
A similar problem
I'm creating an application to scan for Bluetooth low energy devices and have implemented the scan functionality, however, am getting the error:
fail to start le scan - SecurityException thrown: java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results
I have the required permissions in my manifest, however, am still getting this error. I have done some research and read that SDK versions > 23 require some kind of manual checking for permissions, is this the correct solution to this problem or is there a simpler alternative?
package com.example.jake.bluetooth;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private String ble_not_supported = "BLE not supported";
private BluetoothManager bluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private Button startScanBtn;
private boolean mScanning;
private Handler mHandler;
private BluetoothAdapter.LeScanCallback mLeScanCallBack;
private static final long SCAN_PERIOD = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
startScanBtn = findViewById(R.id.start_scan);
mHandler = new Handler();
mScanning = true;
mLeScanCallBack = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int rssi, byte[] bytes) {
}
};
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Toast.makeText(this, ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
startScanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanLeDevice(mScanning);
}
});
}
private void scanLeDevice(final boolean enable){
if(enable){
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallBack);
}
},SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallBack);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallBack);
}
}
}
No it's not enough to just have it in your manifest. You must also explicitly ask the user at runtime. See https://developer.android.com/training/permissions/requesting for more info.
It's 2020, but I respond to this question anyway so maybe it will be helpfull for someone. I encauntered this problem and I resolved it with adding this line of code in onCreate call: requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);. You're just asking to the user to allow access location. Obvisully PERMISSION_REQUEST_COARSE_LOCATION is defined like: private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;.
I've a app to use BLE and this is my AndroidManifest.xml file, all works fine.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothlowenergy_gatt_sendreceive">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ServiceActivity"></activity>
</application>
</manifest>
You should uninstall previous build:
Run > Edit Configurations > Application > Before launch section(on the right)
Create a gradle-aware Make add :app:uninstallAll
So I have a Share button that will share an image and a body of text.
On Nougat (API 25) and Oreo (API 26), it works absolutely perfectly. But when it comes to a couple older version it doesn't work as expected.
Marshmallow (API 23): Inserts the image just fine but no body of text.
Lollipop (API 22): Crashes when you push the Share button with popup error "Unfortunately, Messaging has stopped." LOGCAT isn't showing me any errors when this happens.
Here is my share button code:
if (id == R.id.action_shareWine) {
Intent intentShare = new Intent(Intent.ACTION_SEND);
intentShare.putExtra(intentShare.EXTRA_STREAM, imageURI);
intentShare.setType("image/*");
intentShare.putExtra(Intent.EXTRA_TEXT, "body of text goes here");
if (intentShare.resolveActivity(getPackageManager()) != null) {
startActivity(intentShare);
}
return true;
}
Here is a picture to give a visual idea of whats going on:
Anyone have any ideas what could be going on here?
UPDATE 1
Here is the crash log for the Lollipop emulator:
FATAL EXCEPTION: Mms-1
Process: com.android.mms, PID: 7570
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Which I'm not sure why it is happening because the cursor is loading the image just fine in an ImageView in that same activity.
Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) on the ACTION_SEND Intent, to allow third parties the ability to read the content identified by the Uri.
Also, since the image would appear to be a JPEG (based on the file extension), the MIME type is image/jpeg, not image/* or image/png.
For More Details
working in Oreo and Marshmallow Version Read this
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
Source Code
https://drive.google.com/open?id=1vfO43dMSt096CMp6nrOJNl3fJAf6MPwG
create xml folder inside providers_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.holostik.sharescreenshotexample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.holostik.sharescreenshotexample.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
</application>
</manifest>
package com.holostik.sharescreenshotexample;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.holostik.sharescreenshotexample.share.ScreenshotType;
import com.holostik.sharescreenshotexample.share.ScreenshotUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int n;
String photoPath;
LinearLayout rootContent;
ImageView iv_share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootContent = (LinearLayout) findViewById(R.id.rootContent);
iv_share = (ImageView) findViewById(R.id.iv_share);
iv_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("MainActivity ", "P granted");
takeScreenshot(ScreenshotType.FULL);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
takeScreenshot(ScreenshotType.FULL);
}
}
});
}
/* Method which will take screenshot on Basis of Screenshot Type ENUM */
private void takeScreenshot(ScreenshotType screenshotType) {
Bitmap b = null;
switch (screenshotType) {
case FULL:
b = ScreenshotUtils.getScreenShot(rootContent);
break;
case CUSTOM:
//If Screenshot type is CUSTOM
break;
}
//If bitmap is not null
if (b != null) {
// showScreenShotImage(b);//show bitmap over imageview
Log.e("keshav", "bitmap is -- > " + b);
SaveImage(b);
shareScreenshot();
/* File saveFile = ScreenshotUtils.getMainDirectoryName(MainActivity.this);//get the path to save screenshot
File file = ScreenshotUtils.store(b, "screenshot" + screenshotType + ".jpg", saveFile);//save the screenshot to selected path
shareScreenshot(file);//finally share screenshot
Log.e("file Path", String.valueOf(file));
*/
} else
//If bitmap is null show toast message
Toast.makeText(MainActivity.this, R.string.screenshot_take_failed, Toast.LENGTH_SHORT).show();
}
private void SaveImage(Bitmap finalBitmap)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/* TODO Show screenshot Bitmap */
// private void showScreenShotImage(Bitmap b) {
// imageView.setImageBitmap(b);
// }
private void shareScreenshot()
{
photoPath = Environment.getExternalStorageDirectory() + "/saved_images" + "/Image-" + n + ".jpg";
File F = new File(photoPath);
//Uri U = Uri.fromFile(F);
// Uri U = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".my.package.name.provider", F);
// TODO your package name as well add .fileprovider
Uri U = FileProvider.getUriForFile(MainActivity.this.getApplicationContext(), "com.holostik.sharescreenshotexample.fileprovider", F);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_STREAM, U);
startActivityForResult(Intent.createChooser(i, "Email:"), 1);
}
// TODO Share Screen SHOT End ..............
}
I want to programing app for data track in background , so I use service .
I want to write a program that monitors all data sent and received by the device, and when the total volume of received or received messages reaches a specified value, the Internet device is turned off.
So I used the following code to monitor the data:
mStartRX = TrafficStats.getTotalRxBytes ();
mStartTX = TrafficStats.getTotalTxBytes ();
And I used the services to work on the background in the background.
To specify the download or upload limit from the user with edittext, I requested this limit in mainactivity and send this value to the service.
The problem is when: When I destroy the program, I will restart the service and get the NULL value and the program crashes.
My application code:
Main Activity :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static Handler mHandler = new Handler();
public static long UPP;
public static long DLL;
Button startService,stopService;
public Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (FirstService.mStartRX == TrafficStats.UNSUPPORTED || FirstService.mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
startService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText UP = (EditText) findViewById(R.id.UP);
String UPPP = UP.getText().toString();
UPP=Long.parseLong(UPPP);
EditText DL = (EditText) findViewById(R.id.DL);
String DLLL = DL.getText().toString();
DLL=Long.parseLong(DLLL);
Intent intent = new Intent(getApplicationContext(), FirstService.class);
String myString = DLLL;
intent.putExtra("StringName", myString);
startService(intent);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(),FirstService.class));
}
});
}
public final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
RX.setText(Long.toString(FirstService.rxBytes));
TX.setText(Long.toString(FirstService.txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
Service :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.widget.TextView;
import android.widget.Toast;
public class FirstService extends Service{
public static long mStartRX ;
public static long mStartTX ;
public static long rxBytes ;
public static long txBytes ;
public long dl=MainActivity.DLL;
Context context=this;
private final Runnable mRunnable = new Runnable() {
public void run() {
rxBytes = (TrafficStats.getTotalRxBytes()- mStartRX)/1048576;
txBytes = (TrafficStats.getTotalTxBytes()- mStartTX)/1048576;
if (rxBytes==2) {
stopService(new Intent(getBaseContext(),FirstService.class));
Intent i = new Intent(context,MainActivity.class);
context.startActivity(i);
// WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// wifiManager.setWifiEnabled(false);
//معرفی توست برای نمایش یک پیام کوتاه به کاربر در هنگام خاموش کردن وای فای
Toast.makeText(FirstService.this, "هشدار", Toast.LENGTH_LONG).show();
}
mHandler.postDelayed(mRunnable, 1000);
}
};
private Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"staart",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
mHandler.postDelayed(mRunnable, 1000);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
TrafficStats.clearThreadStatsTag();
Toast.makeText(this,"FirstService Stoped",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
super.onDestroy();
}
}
AndroidManifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.alexandre9009.service">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirstService"
>
</service>
</application>
</manifest>
please help me ...
The problem is with this line
public long dl=MainActivity.DLL;
You're referring to a variable in the Activity, surly when the Activity is destroyed, this variable is no longer in scope, thus you get Null Exception.
You must get this value using the intent.
The other problem is that you can't prevent any service from being killed by the system except foreground services which need to show a notification to the user. But this is not suitable for your situation.
Therefore, the best approach for you is to check whether intent is null or not. If it is not null, you get the value and save it into Preferences or Database or somewhere, if it is null, you retrieve the value from where you stored it before.
I want to learn how to use services in my application, but Service doesn't work! Here is my code.
This is the sample code i have written for the services. Suggest me if i am missing anything.Thanks in Advance
package com.example.utente.test;
import android.content.Intent
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
final String[] numeri =
{"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"
,"1","2","1","2",
"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2",
"1","2","1","2"};
long inizio;
long fine;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizio = System.currentTimeMillis();
Intent i= new Intent(getApplicationContext(), MyService.class);
startService(i);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.riga, numeri);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onResume()
{
super.onResume();
inizio = System.currentTimeMillis();
// new MyService(inizio);
}
#Override
public void onItemClick(AdapterView<?> adattatore, final View componente,
int posizione, long id )
{
Toast.makeText(getApplicationContext(), numeri[posizione],
Toast.LENGTH_LONG).show();
}
}
package com.example.utente.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
long inizio;
long fine;
long tempo;
boolean ciclo=true;
int prova=0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// This is where you would place your code that you want in the
background
// Putting your while loop here will make sure it runs when the app is closed
Toast.makeText(getApplicationContext() ,"COMMAND",
Toast.LENGTH_LONG).show();
while(ciclo)
{
fine = System.currentTimeMillis();
tempo = (fine-inizio)/1000;
if(tempo>10 && prova==0)
{
prova++;
Toast.makeText(getApplicationContext(), "10s",
Toast.LENGTH_LONG).show();
}
}
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
<?xml version="1.0" encoding="utf-8"?>
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.utente.test">
<service
android:name="MyService" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Add your Service to your Manifest as followed:
<service android:name=".MyService" />