How to prevent opening status bar menu in android on Api 31 - General Topics

I could prevent opening the status bar in < API 31 , but in API 31 doesn't work
some codes are deprecated in this version like :
Code:
val closeIntent = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
I used this code to prevent opening the status bar drawer :
JavaScript:
// To keep track of activity's window focus
var currentFocus = false
// To keep track of activity's foreground/background status
var isPaused = false
lateinit var collapseNotificationHandler: Handler
fun collapseNow() {
collapseNotificationHandler = Handler()
if (!currentFocus && !isPaused) {
collapseNotificationHandler.postDelayed(object : Runnable {
override fun run() {
// Use reflection to trigger a method from 'StatusBarManager'
val statusBarService = getSystemService("statusbar")
var statusBarManager: Class<*>? = null
try {
statusBarManager = Class.forName("android.app.StatusBarManager")
} catch (e: ClassNotFoundException) {
e.printStackTrace()
}
var collapseStatusBar: Method? = null
try {
// Prior to API 17, the method to call is 'collapse()'
// API 17 onwards, the method to call is `collapsePanels()`
collapseStatusBar = if (Build.VERSION.SDK_INT > 16) {
statusBarManager!!.getMethod("collapsePanels")
} else {
statusBarManager!!.getMethod("collapse")
}
} catch (e: NoSuchMethodException) {
e.printStackTrace()
}
if (collapseStatusBar != null) {
collapseStatusBar.setAccessible(true)
}
try {
if (collapseStatusBar != null) {
collapseStatusBar.invoke(statusBarService)
}
} catch (e: IllegalArgumentException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
}
// Check if the window focus has been returned
// If it hasn't been returned, post this Runnable again
// Currently, the delay is 100 ms. You can change this
// value to suit your needs.
if (!currentFocus && !isPaused) {
collapseNotificationHandler.postDelayed(this, 100L)
}
}
}, 300L)
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
currentFocus = hasFocus;
if (!hasFocus) {
collapseNow()
}
}
I review all of google developers docs for this problem but unfortunately google codes are deprecated and don't have a clear document for that

HI, i have the same issue, you found anything to solve this problem?

danielsantb said:
HI, i have the same issue, you found anything to solve this problem?
Click to expand...
Click to collapse
I used Device Manager for controlling status Bar but it's not true way, but I solved my problem with this method

Related

[Q][VB.NET] Access remote XML services

EDIT: Development continued Working hard
Hello everyone
I'm trying to port my WIP Infosode from Android (Adobe AIR) to Windows Phone 7, and I have some big problems figuring out how to access a remote XML service, in this case http://services.tvrage.com/
I've used Visual Basic .NET for both desktop and Windows Mobile applications and now for WP7, so I got some VB.NET experience.
Any help is appreciated and will be noted in the finished application.
Regards
//
IzaacJ
Here is one somewhat dirty way.
Download your data (xml) into the isolated storage. After that process the xml file stored.
Code:
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://path.to/the/" + item + ".xml/"));
static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// If we have results
if (!string.IsNullOrEmpty(e.Result))
{
#region Save to Isolated Storage
try
{
// Isolated Storage Directory
string xmlStorageDirectory = "Profiles";
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
// File Path
string filePath = Path.Combine(xmlStorageDirectory, String.Format("{0}.xml", ActiveID));
// Check if the Directory exists. If not create it
if (!store.DirectoryExists(xmlStorageDirectory))
{
store.CreateDirectory(xmlStorageDirectory);
}
// Use Isolated Storeage to write the file
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, store))
{
// Use the stream to write the file
using (StreamWriter stream = new StreamWriter(fileStream))
{
stream.Write(e.Result.Replace(" & ", " & "));
}
}
}
}
// OMG EXCEPTIONS :(
catch (IsolatedStorageException exception)
{
throw exception;
}
#endregion
#region Reading
using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var file = appStorage.OpenFile("Profiles/" + ActiveID + ".xml", FileMode.Open))
{
XmlReader reader = XmlReader.Create(file);
CharacterDataModel profile = new CharacterDataModel();
List<PlayerTraitsModel> traits = new List<PlayerTraitsModel>();
PlayerTraitsModel trait = new PlayerTraitsModel();
bool isCdata = false;
bool isPdata = false;
// While we read the data
while (reader.Read())
{
#region Character
if (reader.Name == "cdata") isCdata = true;
if (isCdata)
{
if (reader.NodeType == XmlNodeType.Element)
{
#region Check for the following values and shallow copy that to the model
//string item = reader.ReadElementContentAsString();
switch (reader.Name)
{
case "id":
profile.id = reader.ReadElementContentAsString();
break;
}
#endregion
}
}
if (reader.NodeType == XmlNodeType.EndElement && reader.Name.Contains("cdata"))
isCdata = false;
#endregion
}
}
}
#endregion
}
}
Thanks for that
Will try to adopt it to VB.NET and see if it will work
At least it's something that I could use until I find a better way.
Regards
Hi,
Use the OpenReadCompleted event of the WebClient, and then put the result into an XDocument by using an XmlReader; from there it's easy to process it (using LINQ to XML) without having to store the XML anywhere first (i.e. do it all in memory). Here's kind of how I do it C#.
Code:
WebClient client = new WebClient();
// Set up the 'completed' event before loading anything
client.OpenReadCompleted += (sender, e) =>
{
if (e.Error != null)
{
if (e.Error is WebException)
{
... Either a connection error, or an invalid status code has been returned. You can determine which using code.
}
else
... // some other exception
return;
}
// Turn the result into an XDocument and parse using LINQ
try
{
Stream aStream = e.Result;
XmlReader anXmlStream = XmlReader.Create(aStream);
XDocument ourXDocument = XDocument.Load(anXmlStream);
// Parse the XML here - best to use 'Linq to XML' to do it
List<TvShow> TVShows = from aShow in ourXDocument.Descendants("show")
select new TvShow() {
ShowName = aShow.Element("name").Value,
Link = aShow.Element("link").Value
};
//////////////////
str.Close();
// if here it all went to plan
}
catch (XmlException xe)
{
...
}
catch (Exception ge)
{
...
}
};
// Here's the bit that actually sets it going
try
{
client.OpenReadAsync(new Uri(URL, UriKind.Absolute));
}
catch (OutOfMemoryException)
{
... Handle the exception
}
catch (StackOverflowException)
{
... Handle the exception
}
catch (Exception ge)
{
... Handle the exception
}
If you're doing this kind of thing a lot it's good to set it up as reusable class that either has it's own events (e.g. ItemsLoaded, ErrorOccured, and ProcessItems) that can be subscribed to, or if you prefer you can have them as methods to override so that you can use it as a web service loading base class from which you can inherit.
Hope that helps. Good luck with it
Ian
otherworld said:
Hi,
Use the OpenReadCompleted event of the WebClient, and then put the result into an XDocument by using an XmlReader; from there it's easy to process it (using LINQ to XML) without having to store the XML anywhere first (i.e. do it all in memory). Here's kind of how I do it C#.
Code:
WebClient client = new WebClient();
// Set up the 'completed' event before loading anything
client.OpenReadCompleted += (sender, e) =>
{
if (e.Error != null)
{
if (e.Error is WebException)
{
... Either a connection error, or an invalid status code has been returned. You can determine which using code.
}
else
... // some other exception
return;
}
// Turn the result into an XDocument and parse using LINQ
try
{
Stream aStream = e.Result;
XmlReader anXmlStream = XmlReader.Create(aStream);
XDocument ourXDocument = XDocument.Load(anXmlStream);
// Parse the XML here - best to use 'Linq to XML' to do it
List<TvShow> TVShows = from aShow in ourXDocument.Descendants("show")
select new TvShow() {
ShowName = aShow.Element("name").Value,
Link = aShow.Element("link").Value
};
//////////////////
str.Close();
// if here it all went to plan
}
catch (XmlException xe)
{
...
}
catch (Exception ge)
{
...
}
};
// Here's the bit that actually sets it going
try
{
client.OpenReadAsync(new Uri(URL, UriKind.Absolute));
}
catch (OutOfMemoryException)
{
... Handle the exception
}
catch (StackOverflowException)
{
... Handle the exception
}
catch (Exception ge)
{
... Handle the exception
}
If you're doing this kind of thing a lot it's good to set it up as reusable class that either has it's own events (e.g. ItemsLoaded, ErrorOccured, and ProcessItems) that can be subscribed to, or if you prefer you can have them as methods to override so that you can use it as a web service loading base class from which you can inherit.
Hope that helps. Good luck with it
Ian
Click to expand...
Click to collapse
Thanks
I'm building a class with functions for fetching and storing the returned XML requests.
It's smart to store it in the IsoStorage so that the data is available offline as well and it will only download the new XML's if it's updated on the server
I think it will make the application a bit more useful.
Regards
EDIT: I've tried to port the first example from MJCS to VB.Net without success. The app closes itself when it's supposed to search and get results from the server. The URL to the generated XML (including parameters) is http://services.tvrage.com/feeds/search.php?key=[MY_API_KEY]&show=[SHOW_NAME]
The code as for now is this:
Code:
Public Function Search(ByVal SearchString As String) As String
Dim Url As New Uri(XMLUrl & "feeds/search.php?key=" & APIKey & "&show=" & SearchString)
'XMLUrl = http://services.tvrage.com/
'APIKey = My API key from TVRage.com
'SearchString = The showname to be searched for in the database
XML.DownloadStringAsync(Url)
Return 0
End Function
Any ideas?
Regards

[Q] Alawyas report network not available when using NewtorkInfo program

0 down vote favorite
share [g+] share [fb] share [tw]
I have wrote a program to check if the network is available or not. Here is my simple code:
Code:
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity=ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
boitealerte(this.getString(R.string.alert),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
I run it on my Android phone, it always returns false but the network is available and I can make calls. Any suggestions>.

[Q] Audio Level Meter

Hello
I'm new to programming and I'm trying to make a java application that will "hear" (not record necessarily) the sound and display how loud is.I'm thinking of converting the sound recordings to numbers,so I can see the difference on the sound levels.I got this code and I added the "getLevel()" method,which returns the amplitude of the current recording,but it's returning -1 everytime.I guess I'm not using it properly. Any ideas how I must call this method?I have to deliver my project in a week,so any help will be much appreciated!
Code:
public class Capture extends JFrame {
protected boolean running;
ByteArrayOutputStream out;
public Capture() {
super("Capture Sound Demo");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container content = getContentPane();
final JButton capture = new JButton("Capture");
final JButton stop = new JButton("Stop");
final JButton play = new JButton("Play");
capture.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(false);
ActionListener captureListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
capture.setEnabled(false);
stop.setEnabled(true);
play.setEnabled(false);
captureAudio();
}
};
capture.addActionListener(captureListener);
content.add(capture, BorderLayout.NORTH);
ActionListener stopListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
capture.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
running = false;
}
};
stop.addActionListener(stopListener);
content.add(stop, BorderLayout.CENTER);
ActionListener playListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
playAudio();
}
};
play.addActionListener(playListener);
content.add(play, BorderLayout.SOUTH);
}
private void captureAudio() {
try {
final AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(
TargetDataLine.class, format);
final TargetDataLine line = (TargetDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int)format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
out = new ByteArrayOutputStream();
running = true;
try {
while (running) {
int count =
line.read(buffer, 0, buffer.length);
if (count > 0) {
out.write(buffer, 0, count);
System.out.println(line.getLevel()); // |-this is what i added-|
}
}
out.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-1);
}
}
};
Thread captureThread = new Thread(runner);
captureThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-2);
}
}
private void playAudio() {
try {
byte audio[] = out.toByteArray();
InputStream input =
new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais =
new AudioInputStream(input, format,
audio.length / format.getFrameSize());
DataLine.Info info = new DataLine.Info(
SourceDataLine.class, format);
final SourceDataLine line = (SourceDataLine)
AudioSystem.getLine(info);
line.open(format);
line.start();
Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate()
* format.getFrameSize();
byte buffer[] = new byte[bufferSize];
public void run() {
try {
int count;
while ((count = ais.read(
buffer, 0, buffer.length)) != -1) {
if (count > 0) {
line.write(buffer, 0, count);
}
}
line.drain();
line.close();
} catch (IOException e) {
System.err.println("I/O problems: " + e);
System.exit(-3);
}
}
};
Thread playThread = new Thread(runner);
playThread.start();
} catch (LineUnavailableException e) {
System.err.println("Line unavailable: " + e);
System.exit(-4);
}
}
private AudioFormat getFormat() {
float sampleRate = 8000;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = true;
return new AudioFormat(sampleRate,
sampleSizeInBits, channels, signed, bigEndian);
}
@SuppressWarnings("deprecation")
public static void main(String args[]) {
JFrame frame = new Capture();
frame.pack();
frame.show();
}
}
Ok,I managed to make it capture audio and print on a xls file the timestamp and the value of the current sample,but there is a problem : even I've put some spaces between the time and the value and it seems that they are in different columns,they are actualy on the same column of the xls,it's just expanded and covers the next column (I can put a print screen if you don't understand).How can I make it print the data of time and amplitude in two different columns?Here's my code of the class which creates the file and saves the data on xls :
Code:
package soundRecording;
import java.io.File;
import java.util.Formatter;
public class Save {
static Formatter y;
public static void createFile() {
Date thedate = new Date();
final String folder = thedate.curDate();
final String fileName = thedate.curTime();
try {
String name = "Time_"+fileName+".csv";
y = new Formatter(name);
File nof = new File(name);
nof.createNewFile();
System.out.println("A new file was created.");
}
catch(Exception e) {
System.out.println("There was an error.");
}
}
public void addValues(byte audio) {
Date d = new Date();
y.format("%s " + " %s%n",d.curTime(), audio);
}
public void closeFile() {
y.close();
}
}

[TUT] SmartWatch App Development - Part 4 - Beginner

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
In previous article, we looked at Notification API with Hello SmartWatch demo. In this article, we will focus on Control API.
http://forum.xda-developers.com/smartwatch/sony/tut-introduction-smart-watch-t2807896
http://forum.xda-developers.com/smartwatch/sony/tut-smartwatch-app-development-part-2-t2807954
http://forum.xda-developers.com/smartwatch/sony/tut-smartwatch-app-development-part-3-t2807966
Control API is responsible for
Extension lifecycle: It allows you to start and stop extension using Intent. Extension means SmartWatch Host application.
Control.Intents.CONTROL_START_INTENT
Control.Intents.CONTROL_STOP_INTENT.
Controlling the display: Normally we don't require to control the display. Default screen state is "Auto", for the specific need you can change screen state by using Intent.
Control.Intents.SCREEN_STATE_OFF
Control.Intents.SCREEN_STATE_AUTO
Control.Intents.SCREEN_STATE_DIM
Control.Intents.SCREEN_STATE_ON
Controlling the LEDs: It used to switch on /off LEDs based on notification.
Control.Intents.CONTROL_LED_INTENT
Controlling the vibrator: It allows you to vibrate SmartWatch.
Control.Intents.CONTROL_VIBRATE_INTENT
Key event: It is used to capture hardware key i.e. home, back and menu key, which is available in SmartWatch2.
Control.Intents.CONTROL_KEY_EVENT_INTENT
Touch event: It is used to capture touch events.
Control.Intents.CONTROL_TOUCH_EVENT_INTENT
Control.Intents.CONTROL_SWIPE_EVENT_INTENT
Control.Intents.CONTROL_OBJECT_CLICK_EVENT_INTENT
Sony's Add-on SDK version 2.0 supports ListView and GridView but this article focuses on basic controls only. For the demo I will create a simple layout with ImageView and TextView. I will animate ImageView with thread and also capture onClick event of ImageView.
Screen Shots
Open Accessory emulator and select SmartWatch 2
Select Control API
Select Hello SmartWatch Extension
Enjoy dancing android
Click on Android will fire onClick event from host app to extension app
Click on menu hardware button to make menu item visible.
Step 1: Create java class named "HelloControlSmartWatch2.java" and extend with ControlExtension.
Code:
package com.kpbird.hellosmartwatch;
import android.content.Context;
import android.location.Address;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.sonyericsson.extras.liveware.aef.control.Control;
import com.sonyericsson.extras.liveware.extension.util.control.ControlExtension;
import com.sonyericsson.extras.liveware.extension.util.control.ControlObjectClickEvent;
import com.sonyericsson.extras.liveware.extension.util.control.ControlTouchEvent;
import com.sonyericsson.extras.liveware.extension.util.control.ControlView;
import com.sonyericsson.extras.liveware.extension.util.control.ControlView.OnClickListener;
import com.sonyericsson.extras.liveware.extension.util.control.ControlViewGroup;
public class HelloControlSmartWatch2 extends ControlExtension {
private static final int ANIMATION_DELTA_MS = 500;
private static final int MENU_ITEM_0 = 0;
private static final int MENU_ITEM_1 = 1;
private static final int MENU_ITEM_2 = 2;
private boolean mIsShowingAnimation = false;
private Animation mAnimation = null;
private Handler mHandler;
private ControlViewGroup mLayout = null;
private String TAG = this.getClass().getSimpleName();
private Bundle[] mMenuItemsText = new Bundle[3];
public HelloControlSmartWatch2(Context context, String hostAppPackageName,Handler handler) {
super(context, hostAppPackageName);
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
mHandler = handler;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.hello_control_2, null);
mLayout = parseLayout(layout);
if(mLayout !=null){
ControlView androidAnim = mLayout.findViewById(R.id.imgHelloControl);
androidAnim.setOnClickListener(new OnClickListener() {
@Override
public void onClick() {
Toast.makeText(mContext, "Button Clicked", Toast.LENGTH_LONG).show();
Log.i(TAG, "Android Button Clicked");
toggleAnimation();
}
});
}
mMenuItemsText[0] = new Bundle();
mMenuItemsText[0].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_0);
mMenuItemsText[0].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, "Item 1");
mMenuItemsText[1] = new Bundle();
mMenuItemsText[1].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_1);
mMenuItemsText[1].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, "Item 2");
mMenuItemsText[2] = new Bundle();
mMenuItemsText[2].putInt(Control.Intents.EXTRA_MENU_ITEM_ID, MENU_ITEM_2);
mMenuItemsText[2].putString(Control.Intents.EXTRA_MENU_ITEM_TEXT, "Item 3");
}
@Override
public void onResume() {
super.onResume();
showLayout(R.layout.hello_control_2, null);
startAnimation();
}
@Override
public void onPause() {
super.onPause();
stopAnimation();
}
@Override
public void onDestroy() {
stopAnimation();
mHandler = null;
};
public static int getSupportedControlWidth(Context context) {
return context.getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_width);
}
public static int getSupportedControlHeight(Context context) {
return context.getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_height);
}
@Override
public void onTouch(ControlTouchEvent event) {
Log.i(TAG, "onTouch() " + event.getAction());
}
@Override
public void onObjectClick(ControlObjectClickEvent event) {
Log.i(TAG, "onObjectClick() " + event.getClickType());
if (event.getLayoutReference() != -1) {
mLayout.onClick(event.getLayoutReference());
}
}
@Override
public void onKey(int action, int keyCode, long timeStamp) {
Log.i(TAG, "onKey() " + action + "\t" + keyCode + "\t" + timeStamp);
if (action == Control.Intents.KEY_ACTION_RELEASE
&& keyCode == Control.KeyCodes.KEYCODE_OPTIONS) {
showMenu(mMenuItemsText);
}
}
@Override
public void onMenuItemSelected(int menuItem) {
Log.d(TAG, "onMenuItemSelected() - menu item " + menuItem);
if (menuItem == MENU_ITEM_0) {
clearDisplay();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
onResume();
}
}, 1000);
}
}
private void toggleAnimation() {
if (mIsShowingAnimation) {
stopAnimation();
}
else {
startAnimation();
}
}
private void startAnimation() {
if (!mIsShowingAnimation) {
mIsShowingAnimation = true;
mAnimation = new Animation();
mAnimation.run();
}
}
private void stopAnimation() {
if (mIsShowingAnimation) {
// Stop animation on accessory
if (mAnimation != null) {
mAnimation.stop();
mHandler.removeCallbacks(mAnimation);
mAnimation = null;
}
mIsShowingAnimation = false;
}
}
private class Animation implements Runnable {
private int mIndex = 1;
private boolean mIsStopped = false;
Animation() {
mIndex = 1;
}
public void stop() {
mIsStopped = true;
}
@Override
public void run() {
int resourceId;
switch (mIndex) {
case 1:
resourceId = R.drawable.dancing_android_0;
break;
case 2:
resourceId = R.drawable.dancing_android_1;
break;
default:
Log.e(TAG, "mIndex out of bounds: " + mIndex);
resourceId = R.drawable.dancing_android_0;
break;
}
mIndex++;
if (mIndex > 2) {
mIndex = 1;
}
if (!mIsStopped) {
updateAnimation(resourceId);
}
if (mHandler != null && !mIsStopped) {
mHandler.postDelayed(this, ANIMATION_DELTA_MS);
}
}
private void updateAnimation(int resourceId) {
sendImage(R.id.imgHelloControl, resourceId);
}
};
}
Step 2: Open HelloExtensionService.java and override "createExtensionControl" method. In this method we need to identify accessory type before creating object of HelloControlSmartWatch2 class. To identify accessory type ExtensionUtils class has method named "DeviceInfoHealper".
Code:
@Override
public ControlExtension createControlExtension(String hostAppPackageName) {
// First we check if the API level and screen size required for
// SampleControlSmartWatch2 is supported
boolean advancedFeaturesSupported = DeviceInfoHelper.isSmartWatch2ApiAndScreenDetected(this, hostAppPackageName);
if (advancedFeaturesSupported) {
return new HelloControlSmartWatch2(this,hostAppPackageName, new Handler());
} else {
return null;
}
}
Step 3: Open HelloRegistrationInformation.java and change return value from 0 to 2 of "getRequiredControlApiVersion" method, 0 means our example doesn't require Control API, 1 and 2 represent minimum version of API required. We also need to override method named "isDisplaySizeSupported" for the confirmation of Display Size.
Code:
...
...
@Override
public int getRequiredControlApiVersion() {
return 2;
}
....
@Override
public boolean isDisplaySizeSupported(int width, int height) {
return ((width == HelloControlSmartWatch2.getSupportedControlWidth(mContext)
&& height == HelloControlSmartWatch2
.getSupportedControlHeight(mContext) || width == HelloControlSmartWatch2
.getSupportedControlWidth(mContext) && height == HelloControlSmartWatch2
.getSupportedControlHeight(mContext)) );
}
...
...
Step 4: Finally, Open AndroidManiFest.xml and add following action in HelloExtensionReceiver. It will require to capture onClick, onTouch and onObject click event.
Code:
...
...
<action android:name="com.sonyericsson.extras.aef.control.TOUCH_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.SWIPE_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.OBJECT_CLICK_EVENT" />
<action android:name="com.sonyericsson.extras.aef.control.MENU_ITEM_SELECTED" />
...
...
Step 5: Compile & Execute HelloSmartWatch example
Download Source Code​Note: 1. Import project in eclipse 2. Make sure that you change SmartExtensionUtils and SmartExtensionAPI path from project properties.

Editing the stock MTC Manager

Hey guys, I have a xtrons px5 mtcd head unit and I am trying to figure out without flashing to a custom ROM, how to edit what apps launch at wake, or do not turn off with the unit when it goes to sleep.
I believe it is the MTCManager that is doing these actions, and I have found two interesting parts of the decomplied code.
The first file is android/microntek/a.java
HTML:
package android.microntek;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.microntek.service.R;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import java.util.ArrayList;
public class a {
static String cp;
private static boolean cq = false;
static Context cr;
private static int cs = -1;
static Toast ct;
private static final String[] cu = new String[]{"android.microntek.", "com.murtas.", "com.microntek.", "com.goodocom.gocsdk", "android.rockchip.update.service", "com.android.systemui", "com.hct.obd.OBDActivity", "com.unisound", "com.dpadnavi.assist", "com.intel.thermal", "cn.manstep.phonemirror", "com.hiworld.", "com.carboy.launch", "com.android.bluetooth", "net.easyconn", "com.android.launcher", "com.google.android", "com.vayosoft.carsystem"};
static Object cv = new Object();
static a cw;
private static final String[] cx = new String[]{"android.microntek.", "com.murtas.", "com.microntek.", "com.goodocom.gocsdk", "android.rockchip.update.service", "com.android.systemui", "com.hct.obdservice.OBDService", "com.unisound", "com.intel.thermal", "com.dpadnavi.assist", "cn.manstep.phonemirror", "com.android.bluetooth", "com.hiworld.", "net.easyconn", "android.cn.ecar.cds.process.CoreService", "com.google.android", "com.vayosoft.carsystem"};
private a(Context context) {
cr = context;
}
private int ex(Context context) {
int i = 0;
Iterable<e> arrayList = new ArrayList();
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
for (RunningAppProcessInfo runningAppProcessInfo : activityManager.getRunningAppProcesses()) {
int i2 = runningAppProcessInfo.pid;
int i3 = runningAppProcessInfo.uid;
String str = runningAppProcessInfo.processName;
int i4 = activityManager.getProcessMemoryInfo(new int[]{i2})[0].dalvikPrivateDirty;
e eVar = new e();
eVar.fy(i2);
eVar.fz(i3);
eVar.ga(i4);
eVar.gb(str);
eVar.dk = runningAppProcessInfo.pkgList;
arrayList.add(eVar);
String[] strArr = runningAppProcessInfo.pkgList;
}
for (e eVar2 : arrayList) {
int i5;
if (eVar2.gc() < 10000) {
i5 = i;
} else {
String gd = eVar2.gd();
if (gd.indexOf(".") == -1) {
i5 = i;
} else if (fe(gd) || ff(context, gd) || fg(context, gd)) {
i5 = i;
} else if (cs != 0 || fd(gd)) {
try {
activityManager.killBackgroundProcesses(gd);
i5 = i + 1;
} catch (Exception e) {
System.out.println(" deny the permission");
i5 = i;
}
} else {
ez(gd);
i5 = i + 1;
}
}
i = i5;
}
return i;
}
private void ey(Context context) {
Iterable<RunningServiceInfo> runningServices = ((ActivityManager) context.getSystemService("activity")).getRunningServices(100);
System.out.println(runningServices.size());
Iterable<b> arrayList = new ArrayList();
for (RunningServiceInfo runningServiceInfo : runningServices) {
int i = runningServiceInfo.pid;
int i2 = runningServiceInfo.uid;
String str = runningServiceInfo.process;
long j = runningServiceInfo.activeSince;
int i3 = runningServiceInfo.clientCount;
ComponentName componentName = runningServiceInfo.service;
String shortClassName = componentName.getShortClassName();
String packageName = componentName.getPackageName();
PackageManager packageManager = context.getPackageManager();
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
b bVar = new b();
bVar.fh(applicationInfo.loadIcon(packageManager));
bVar.fi(applicationInfo.loadLabel(packageManager).toString());
bVar.fj(shortClassName);
bVar.fk(packageName);
Intent intent = new Intent();
intent.setComponent(componentName);
bVar.fl(intent);
bVar.fm(i);
bVar.fn(i2);
bVar.fo(str);
arrayList.add(bVar);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
for (b bVar2 : arrayList) {
if (bVar2.fp() >= 10000) {
String fq = bVar2.fq();
if (!(fd(fq) || ff(context, fq) || fg(context, fq))) {
if (cs != 0 || fe(fq)) {
try {
context.stopService(bVar2.fr());
} catch (SecurityException e2) {
System.out.println(" deny the permission");
}
} else {
ez(fq);
}
}
}
}
}
private long fa(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
MemoryInfo memoryInfo = new MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
return memoryInfo.availMem;
}
public static a fc(Context context) {
a aVar;
synchronized (cv) {
if (cw == null) {
cw = new a(context);
}
cs = -1;
aVar = cw;
}
return aVar;
}
private boolean fd(String str) {
for (String startsWith : cx) {
if (str.startsWith(startsWith)) {
return true;
}
}
return cp != null && str.equals(cp);
}
private boolean fe(String str) {
for (String startsWith : cu) {
if (str.startsWith(startsWith)) {
return true;
}
}
return cp != null && str.equals(cp);
}
private boolean ff(Context context, String str) {
if (context == null || TextUtils.isEmpty(str)) {
return false;
}
for (InputMethodInfo packageName : ((InputMethodManager) context.getSystemService("input_method")).getInputMethodList()) {
if (str.equalsIgnoreCase(packageName.getPackageName())) {
return true;
}
}
return false;
}
private boolean fg(Context context, String str) {
try {
for (ResolveInfo resolveInfo : context.getPackageManager().queryIntentServices(new Intent("android.service.wallpaper.WallpaperService"), 128)) {
if (str.equalsIgnoreCase(resolveInfo.serviceInfo.packageName)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void ew(int i, String str) {
cs = i;
cq = true;
cp = str;
long fa = fa(cr);
ey(cr);
int ex = ex(cr);
long fa2 = fa(cr);
if (i == 1) {
fa = Math.abs(fa2 - fa);
CharSequence string = cr.getString(R.string.clear_message, new Object[]{Integer.valueOf(ex), Formatter.formatFileSize(cr, fa)});
if (ct == null) {
ct = Toast.makeText(cr, string, 0);
} else {
ct.cancel();
ct = Toast.makeText(cr, string, 1);
}
ct.show();
}
cq = false;
}
public void ez(String str) {
if (str != null && str.length() != 0) {
try {
((ActivityManager) cr.getSystemService("activity")).forceStopPackage(str);
} catch (SecurityException e) {
System.out.println(" deny the permission");
}
}
}
public boolean fb() {
return cq;
}
}
it appears as though it is listing which apps either stay awake on sleep, or launch at boot. Can anybody confirm this?
And in this file, it looks like it might be controlling the apps in the apploop, maybe...
file is android/microntek/c.java
HTML:
package android.microntek;
import android.microntek.service.R;
public class c {
public static final String[] dg = new String[]{"com.microntek.avin", "com.microntek.dvr", "com.microntek.dvd", "com.microntek.tv", "com.microntek.media", "com.microntek.music", "com.microntek.radio", "com.microntek.ipod", "com.microntek.btMusic", "com.microntek.bluetooth", "com.microntek.civxusb", "com.microntek.tv", "com.microntek.dvr"};
public static final String[] dh = new String[]{"com.microntek.avin", "com.microntek.dvr", "com.microntek.dvd", "com.microntek.tv", "com.microntek.media", "com.microntek.music", "com.microntek.radio", "com.microntek.ipod", "com.microntek.btMusic", "com.microntek.dvr"};
public static final String[] di = new String[]{"com.microntek.radio", "com.microntek.dvd", "com.microntek.music", "com.microntek.media", "com.microntek.ipod", "com.microntek.avin"};
public static final int[] dj = new int[]{R.string.music_style0, R.string.music_style1, R.string.music_style2, R.string.music_style3, R.string.music_style4, R.string.music_style5, R.string.music_style6};
}
Let me know what you guys think.
You are absolutely correct. Check out the thread on the Malaysk ROM for the PX5. A member, Nico84, is working with the same files. You guys may want to join forces on this.
Johan
Thanks for that, does that work on the Stock firmware, or only on Malaysk's Custom ROM?
Not sure, but I believe it will work on stock. Needs to be rooted I suppose. Contact Nico84 for details, I am not an experienced Android developer.
I did, thanks for the lead on that, exactly what I was looking for. It looks like it should work on stock firmware so ill probably give it a try
So I took Nico84's MTCManager and tried to decompile and add spotify and accuweather to it, and recompile it. But then the actualy MTCManager did not work, so not sure what I did wrong.
semaj4712 said:
So I took Nico84's MTCManager and tried to decompile and add spotify and accuweather to it, and recompile it. But then the actualy MTCManager did not work, so not sure what I did wrong.
Click to expand...
Click to collapse
You have to compile it with original signature, not testkeys. You can use "tickle my android"
Bummer, tickle my android does not seem to work on mac which is all I have, is there any other way to compile with original signature with apktools? Or would it be possible to make me a version that allows spotify and accuweather to remain open, that would be great.
Ok so I found the documentation on signatures for the APKtool, but it still didnt work. Just to be clear I started this command
Code:
apktool d MTCManager.apk
then I made the changes to the smali.d file, and then recompiled with this command
Code:
apktool b MTCManager/ -c
Is there something I am doing wrong? (The location of files is not exact, bare in mind I am doing this on a mac via terminal so I simply drag and drop the file which returns the path it needs.)
On second try I was able to get this to work. The above commands worked perfectly, my guess is I messed something up the first time around.
For PX3:
when the unit comes back from sleep it sends Intent com.cayboy.action.ACC_ON
when it goes to sleep it sends com.cayboy.action.ACC_OFF

Categories

Resources